写完后的空文件

时间:2014-04-14 01:51:38

标签: python file

继续尝试写入文件,但文件是空的:-(我尝试了很多东西,觉得我在旋转。我是新手,你可以告诉。任何帮助都将不胜感激!< / p>

import shutil
import re
import csv
import sys      # imports the sys module
infile = csv.reader(open("March9small.csv", "rU"), dialect=csv.excel_tab)
reader=csv.reader(infile)
new_rows_list=[]
for row in infile:
    new_rows_list.append(row)
    print new_rows_list

outfile = csv.writer(open("March9small-revised.csv","wt"), dialect=csv.excel_tab)
for i in new_rows_list:
    outfile.writerow(i)

1 个答案:

答案 0 :(得分:3)

为什么将csv.reader传递给csv.reader

这里是没有带嵌套with上下文管理器的中间列表的简化版本:

import csv

with open("March9small.csv", "rU") as infile:
    with open("March9small-revised.csv","wt") as outfile:
        reader = csv.reader(infile, dialect=csv.excel_tab)
        writer = csv.writer(outfile, dialect=csv.excel_tab)

        for row in reader:
            writer.writerow(row)

确保您了解这里发生了什么 - 如果没有,请随时在评论中提问。