logo

Python의 StringIO 모듈

그것은 스트링IO 모듈은 메모리 내 파일류 객체입니다. 사용자가 일반 파일 객체에서 기대할 수 있는 대부분의 기능을 입력하거나 출력하는 데 사용할 수 있습니다. 사용자가 StringIO 개체를 생성하면 처음에는 생성자에 문자열을 제공하여 생성됩니다. 문자열이 없으면 StringIO는 비어 있습니다. 두 경우 모두 파일에 처음 표시된 커서는 0에서 시작됩니다.

이 모듈은 최신 버전의 Python에서는 사용할 수 없습니다. 따라서 이 모듈을 사용하려면 io.StringIO 형식으로 Python의 Io 모듈로 전송해야 합니다.

예:

 # First, we will import the required module. from io import StringIO as SIO # The arbitrary string. string_1 = 'This is the initialized string.' # Here, we will use the StringIO method for setting as the file object. # Now, we have an object-file that we can treat as a file. file_1 = SIO(string_1) # Now, we will be reading the file by using read() print (file_1.read()) # Here, We can also write in this file. file_1.write(' Welcome to Javatpoint.com.') # by using the following command, we can make the cursor at index 0. file_1.seek(0) # by using the following command, the user is able to print the file after writing #in the initialized string (string_1). print ('The file of the string after writing in it is:', file_1.read()) 

산출:

 This is the initialized string. The file of the string after writing in it is: This is the initialized string. Welcome to Javatpoint.com. 

StringIO의 중요한 방법:

다음은 StringIO의 몇 가지 방법입니다.

1. StringIO.getvalue(): 이 함수는 파일의 전체 내용을 반환하는 데 사용됩니다.

통사론:

위 방법의 구문은 다음과 같습니다.

 File_name.getvalue() 

예:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 = 'Hello and thank you for visiting to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # Retrieving the complete contents of the above file. print(file_1.getvalue()) 

산출:

 Hello and thank you for visiting to Javatpoint.com 

2. 여기서는 부울 값, 즉 false 또는 true를 반환하는 StringIO의 일부 함수를 살펴봅니다.

    이사티():StringIO의 이 함수는 스트림이 대화형이 아닌 경우 False를 반환하고 스트림이 대화형인 경우 True를 반환하는 데 사용됩니다.읽기 가능():StringIO의 이 함수는 파일을 읽을 수 없으면 False를 반환하고 파일을 읽을 수 있으면 True를 반환하는 데 사용됩니다.쓰기 가능():StringIO의 이 함수는 파일이 쓰기를 지원하지 않으면 False를 반환하고 파일이 쓰기를 지원하면 True를 반환하는 데 사용됩니다.검색 가능():StringIO의 이 함수는 파일이 임의 액세스를 지원하지 않으면 False를 반환하고 파일이 임의 액세스를 지원하면 True를 반환하는 데 사용됩니다.닫은:StringIO의 이 함수는 파일이 열려 있는 경우 False를 반환하고, 파일이 닫혀 있으면 True를 반환하는 데 사용됩니다.

통사론:

위 방법의 구문은 다음과 같습니다.

 1. File_name.isatty() 2. File_name.readable() 3. File_name.writable() 4. File_name.seekable() 5. File_name.closed 

예:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 = 'Hello and thank you for visiting to Javatpoint.com.' # Here, we will use the StringIO method for setting # as the file object. file_1 = SIO(string_1) # by using the following command, the user will be able to return is the file #interactive or not. print ('Is the file stream above interactive?', file_1.isatty()) # by using the following command, # the user will be able to return is the file readable or not. print ('Is the file stream above readable?', file_1.readable()) # by using the following command, # the user will be able to return does the file support writing or not. print ('Is the file stream above writable?', file_1.writable()) # by using the following command, , the user will be able to return is the file #seekable or not. print ('Is the file stream above seekable?', file_1.seekable()) # by using the following command, the user will be able to return is the file #closed or not. print ('Is the file above closed?', file_1.closed) 

산출:

 Is the file stream above interactive? False Is the file stream above readable? True Is the file stream above writable True Is the file stream above seekable? True Is the file above closed? False 

3. StringIO.seek(): 그만큼 구하다() 함수는 파일 내에서 커서의 위치를 ​​설정하는 데 사용됩니다. 문서에 쓰기나 읽기 작업을 실행하면 마지막으로 사용한 인덱스에 커서가 놓이게 되어 파일의 시작 위치에서 커서를 이동할 수 있도록 Seek()를 사용합니다.

통사론:

위 방법의 구문은 다음과 같습니다.

 File_name.seek(argument) #This argument tells the function where to place the cursor. 

예:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 ='Hello and thank you for visiting to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # here, the user will be able to Read the file: print (file_1.read()) #If the user wishes to view the file again, it will display empty file since the #cursor has been set to the last index. It will also not print anything because #the function returns an empty string. print (file_1.read()) # So, to set the cursor position for reading or writing the file again # we can use seek() function. #We can pass any index here form(0 to len(file)) file_1.seek(0) # Now the user can read the file again print (file_1.read())S 

산출:

 Hello and thank you for visiting to Javatpoint.com. Hello and thank you for visiting to Javatpoint.com. 

4. StringIO.truncate(): 이 함수는 파일 스트림의 크기를 조정하는 데 사용됩니다. 이 메서드는 파일을 저장하고 지정된 인덱스 뒤에 삭제합니다.

통사론:

위 방법의 구문은 다음과 같습니다.

 File_name.truncate(size = None) # The user can provide the size from where to truncate the file. 

예:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 ='Hello and welcome to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # here, we can read the initial file: print(file_1.read()) # for setting the cursor at 0. file_1.seek(0) # for dropping the file after the given index, i.e., 14. file_1.truncate(14) # here, it will print the File after truncate. print(file_1.read()) 

산출:

 Hello and welcome to Javatpoint.com. Hello and welc 

5. 스트링IO.tell(): 이 방법은 파일의 현재 스트림과 커서 위치를 알려주는 데 사용됩니다.

선반 개

통사론:

위 방법의 구문은 다음과 같습니다.

 File_name.tell() 

예:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 ='Hello and welcome to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # Here the cursor is set at index '0'. print(file_1.tell()) # now, we are setting the Cursor to index '23'. file_1.seek(23) # here, we will be printing the index of cursor print(file_1.tell()) 

산출:

 0 23 

6. 스트링IO.close() 파일을 닫을 때 사용됩니다. 이 함수는 파일에 대해 호출되며 해당 파일에 대해 어떤 작업도 수행할 수 없습니다. 수행된 모든 작업은 다음과 같은 결과를 초래합니다. 값오류 .

구문: =

위 방법의 구문은 다음과 같습니다.

 File_name.close( 

예:

 # First, we will import the StringIO module. from io import StringIO as SIO # The arbitrary string. string_1 ='Hello and welcome to Javatpoint.com.' # Here, we will use the StringIO method for setting as the file object. file_1 = SIO(string_1) # here, we can read the initial file: print(file_1.read()) # for closing the current file. file_1.close() # If the user would perform any operation on the above file now, it will raise an #ValueError. # here, we will be using the closed function to know whether the file is closed #or not. print('Is the file closed?', file_1.closed) 

산출:

 Hello and welcome to Javatpoint.com. Is the file closed? True