Suppose I have a file (say file1.txt) with data around 3mb or more. If I want to write this data to a second file (say file2.txt), which one of the following approaches will be better?
Language used: Python 2.7.3
Approach 1:
file1_handler = file("file1.txt", 'r') for lines in file1_handler: line = lines.strip() # Perform some operation file2_handler = file("file2.txt", 'a') file2_handler.write(line) file2_handler.write('\r\n') file2_handler.close() file1_handler.close() Approach 2:
file1_handler = file("file1.txt", 'r') file2_handler = file("file2.txt", 'a') for lines in file1_handler: line = lines.strip() # Perform some operation file2_handler.write(line) file2_handler.write('\r\n') file2_handler.close() file1_handler.close() I think approach two will be better because you just have to open and close file2.txt once. What do you say?