[英]How to change csv delimiter in same csv file using python?
I'm trying to change the delimiter in a folder that contains a bunch of csv files.我正在尝试更改包含一堆 csv 文件的文件夹中的分隔符。 But this code doesn't seem to work, do you have any idea how I can get over this issue?但是这段代码似乎不起作用,你知道我该如何解决这个问题吗? Thank you in advance for your help.预先感谢您的帮助。
Here's the code:这是代码:
` `
f1 = open(csv_files[i], "r")
f2 = open(csv_files[i], "w")
reader = csv.reader(f1, delimiter=',')
writer = csv.writer(f2, delimiter=';')
writer.writerows(csv_files[i])
print("Delimiter successfully changed")
f1.close()
f2.close()
` `
this:这个:
df = pd.read_csv('student-mat.csv', sep=';', encoding='utf-8')
does not work either.也不起作用。
my suggestion is write the DataFrame to a new CSV file with the desired delimiter.我的建议是使用所需的分隔符将 DataFrame 写入新的 CSV 文件。
import pandas as pd
df = pd.read_csv(csv_files[i], encoding='utf-8')
df.to_csv(f"{csv_files[i]}_modified.csv", sep=';', encoding='utf-8', index=False)
print("Delimiter successfully changed")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.