我有一个包含多个CSV文件的文件夹。这些文件都包含绘制双垂直和水平的框作为分隔符。我试图将所有这些文件导入python,将分隔符更改为管道,然后将新文件保存到另一个位置。我目前运行的代码没有任何错误但实际上没有做任何事情。有什么建议?
import os
import pandas as pd
directory = 'Y:/Data'
dirlist = os.listdir(directory)
file_dict = {}
x = 0
for filename in dirlist:
if filename.endswith('.csv'):
file_dict[x] = pd.read_csv(filename)
column = file_dict[x].columns[0]
file_dict[x] = file_dict[x][column].str.replace('╬', '|')
file_dict[x].to_csv("python/file{}.csv".format(x))
x += 1
这是样本数据的图片:
with i as open(filename):
with o as open(filename+'.new', 'w+):
for line in i.readlines():
o.write(line.replace('╬', '|'))
或者,跳过python,并使用终端中的sed
:
$ sed -i 's/╬/|/g' *.csv
假设原始分隔符没有出现在任何转义字符串中,这应该比使用常规csv
模块稍快一些。 Panada在阅读CSV时似乎做了一些文件系统伏都教,所以如果它同样快,我也不会太惊讶。到目前为止,sed
几乎肯定会击败他们。
我们可以只使用csv库中的内置函数为我们读取文件,然后再次写入,而不是直接用新字符替换出现的字符(也可能替换字符的转义出现)。
import csv
with open('myfile.csv', newline='') as infile, open('outfile.csv', 'w', newline='') as outfile:
reader = csv.reader(infile, delimiter='╬')
writer = csv.writer(outfile, delimiter='|')
for row in reader:
writer.writerow(row)
改编自docs