我在写入CSV文件时遇到问题。此代码有什么问题?
f = open("test.csv", 'w', encoding='utf-8')
with open("sprawdzamy.txt", "r", encoding="utf-8") as plik:
text = plik.read()
tester=text.split("\n")
with open("testdata_hr.csv", "r", encoding="utf-8") as plik:
x = 0
for line in plik:
someList=line.split(",")
if x == 0:
x+=1
continue
for element in tester:
if element in line:
for s in someList:
f.write(s +"\t")
f.write("Good" +'\n')
所以我想获取像这样的文件:
1 2 3 4 5 Good
2 4 5 2 1 Good
但是我得到了这样的东西:
1 2 3 4 5
Good
2 4 5 2 1
Good
答案 0 :(得分:0)
可能想考虑一次写入而不是连续写入。像这样:
write_string = ""
for s in someList:
write_string += f"{s}\t"
f.write(f"{write_string} Good \n")
我觉得应该有一个比这更优雅的解决方案,但是应该可以解决问题。
答案 1 :(得分:0)
这里很少有人担心
1,2,3,4,5,Good
2,4,5,2,1,Good
csv
模块编写csv文件。import csv
with open('employee_file.csv', mode='w') as employee_file:
employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
employee_writer.writerow(['John Smith', 'Accounting', 'November'])
employee_writer.writerow(['Erica Meyers', 'IT', 'March'])
输出文件看起来像
John Smith,Accounting,November
Erica Meyers,IT,March
答案 2 :(得分:0)
您的行似乎包含new line
个字符,因此要删除该字符,请使用rstrip
f = open("test.csv", 'w', encoding='utf-8')
with open("sprawdzamy.txt", "r", encoding="utf-8") as plik:
text = plik.read()
tester=text.split("\n")
with open("testdata_hr.csv", "r", encoding="utf-8") as plik:
x = 0
for line in plik:
someList=line.split(",")
if x == 0:
x+=1
continue
for element in tester:
if element in line:
for s in someList:
f.write(s.rstrip('\n\r') +"\t")
f.write("Good" +'\n')