更好的方法来读取/写入Python中的文件?

问题描述:

假设我有一个文件(比如file1.txt),数据大约3mb或更多。如果我想将这些数据写入第二个文件(如file2.txt),以下哪种方法会更好?更好的方法来读取/写入Python中的文件?

使用语言:Python的2.7.3

方法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() 

方法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() 

我认为方法有两个会更好,因为你只需要一次打开和关闭file2.txt。你说什么?

+2

用[open](http://docs.python.org/2/library/functions.html#open)打开文件,而不是[file](http://docs.python.org/2/库/ functions.html#文件)。 – Matthias 2013-03-20 13:23:04

使用with,它会自动关闭该文件,为您提供:

with open("file1.txt", 'r') as in_file, open("file2.txt", 'a') as out_file: 
    for lines in in_file: 
     line = lines.strip() 
     # Perform some operation 
     out_file.write(line) 
     out_file.write('\r\n') 

使用open,而不是filefile已被弃用。

当然,在file1的每一行上打开file2是不合理的。

+1

我在写同样的想法:) @Hemant,看看:http://docs.python.org/2/whatsnew/2.5.html#pep-343-the-with-statement – 2013-03-20 13:17:24

+0

关于f2.write('\ r \ n'):为了做到这一点,你需要打开f2作为二进制文件(将“b”添加到标志)。 – 2013-03-20 13:19:11

+0

哎呀!我认为开放已被弃用:p(我没有正确地阅读文档) 写作的速度增加了吗?因为方法一复制1 MB数据需要将近2个小时。 – Hemant 2013-03-20 13:19:36

我最近在做类似的事情(如果我理解你的话)。如何:

file = open('file1.txt', 'r') 
file2 = open('file2.txt', 'wt') 

for line in file: 
    newLine = line.strip() 

    # You can do your operation here on newLine 

    file2.write(newLine) 
    file2.write('\r\n') 

file.close() 
file2.close() 

这种方法就像一个魅力!

+0

:很酷..感谢您的方法:) – Hemant 2013-03-20 13:28:33

我的解决方案(从帕维尔Anossov +缓冲派生):

dim = 1000 
buffer = [] 
with open("file1.txt", 'r') as in_file, open("file2.txt", 'a') as out_file: 
    for i, lines in enumerate(in_file): 
     line = lines.strip() 
     # Perform some operation 
     buffer.append(line) 
     if i%dim == dim-1: 
      for bline in buffer: 
       out_file.write(bline) 
       out_file.write('\r\n') 
      buffer = [] 

帕维尔Anossov第一次给了正确的解决方案:这只是一个建议;) 也许它的存在是为了实现这个功能更优雅的方式。如果有人知道,请告诉我们。

+0

@ Francesco:嘿谢谢你的答案:)但我不太熟悉枚举方法。请说明我使用枚举的好处吗? – Hemant 2013-03-21 05:44:05

+0

@Hemant:枚举是有用的:)看看这里:http://docs.python.org/2/library/functions.html#enumerate – 2013-03-21 07:37:31

+0

@ Francesco:谢谢你的文档。现在我更清楚地理解你的例子。 :) – Hemant 2013-03-21 10:32:16