从Python目录中读取文件

时间:2014-07-16 09:21:48

标签: python

我的桌面上有一个包含文件的文件夹,我正在尝试编写一个脚本来读取每个文件,用逗号替换空格,然后将每个文件作为CSV文件返回。

这是我的代码,但它不起作用:

import os
import re
import csv

path = 'C:\Users\Kenny\Desktop\TTUM'
listing = os.listdir(path)
for infile in listing:
    dir_item_path = os.path.join(path, infile)
    fh = open(dir_item_path,'r')
    for line in fh.readlines():
         space_remove = re.sub(r"\s+",",",line.rstrip())
         split_Line = space_remove.split(" ")
         Fname = infile 
         Lname = Fname.split('.')[0]
         name = Lname + ".csv"
         process_file = open(name,"wb")
         newfile = csv.writer(process_file)
         newfile.writerow(split_Line)
         process_file.close()   

1 个答案:

答案 0 :(得分:2)

您正在重新打开文件,写一行,每次都关闭。这将截断文件,只写一行。尝试在for循环之前打开(你已经在使用输入文件),并在完成所有操作后关闭。

path = 'C:\Users\Kenny\Desktop\TTUM'
listing = os.listdir(path)

for infile in listing:
    dir_item_path = os.path.join(path, infile)
    fh = open(dir_item_path,'r')
    Fname = infile 
    Lname = Fname.split('.')[0]
    name = Lname + ".csv"
    process_file = open(name,"wb")
    newfile = csv.writer(process_file)
    for line in fh.readlines():
         space_remove = re.sub(r"\s+",",",line.rstrip())
         split_Line = space_remove.split(" ")
         newfile.writerow(split_Line)
    process_file.close()   

当然,您的脚本可能会出现更多错误,但为此您需要准确解释问题所在。