Python reads Big Data txt and Python reads data txt
If you call the read () method directly for large file objects, unpredictable memory usage may occur. A good way is to use a fixed-length buffer to constantly read the file content. That is, through yield.
When I read two multi-G txt files using Python, I simply used the readlines method, and the result collapsed as soon as the memory was run.
Fortunately, my colleague clicked it and used the yield method to test it without any pressure. The reason is that readlines stores all text content in the memory, while yield is similar to a generator.
The Code is as follows:
def open_txt(file_name): with open(file_name,'r+') as f: while True: line = f.readline() if not line: return yield line.strip()
Call instance:
for text in open_txt('aa.txt'): print text
Example 2:
The target txt file is about 6 GB. If you want to extract the first 1000 pieces of data and save it in a new txt file, perform the remaining operations, although I don't know if this is necessary, I 'd like to test the small data size first. Refer to this post: I want to save a list to a Txt file. How can I save it? I wrote a simple applet myself.
========================================================== ================
import datetimeimport picklestart = datetime.datetime.now()print "start--%s" % (start)fileHandle = open ( 'train.txt' )file2 = open('s_train.txt','w') i = 1while ( i < 10000 ): a = fileHandle.readline() file2.write(''.join(a)) i = i + 1fileHandle.close() file2.close()print "done--%s" % ( datetime.datetime.now() - start)if __name__ == '__main__': pass
========================================================== ================
Pickle is a library that you can talk about. You can take a look at it on the official website.
Articles you may be interested in:
- Use python to split a TXT file into 4 k txt files
- Python reads the file names of all files in the directory and saves them to the txt file code.
- How to import txt data to mysql using Python
- Reading and Writing txt files using different codes in Python
- Python combines TXT files in a directory into a large TXT file