我的桌面上有一个包含文件的文件夹,我试图编写一个脚本来读取每个文件,用逗号替换空格,然后将每个文件作为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()
您将重新打开文件,写一行,然后每次关闭。这将截断文件,只写一行。尝试在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()
当然,您的脚本可能有很多其他错误,但是为此,您需要确切说明问题所在。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句