添加新列时添加了错误行 python
erroneous line added while adding new columns python
我正在尝试在处理输入的 csv 文件后在 csv 文件中添加额外的列。但是,我在输出的每一行之后添加了额外的新行。
我下面的代码中遗漏或错误的地方 -
import csv
with open('test.csv', 'r') as infile:
with open('test_out.csv', 'w') as outfile:
reader = csv.reader(infile, delimiter=',')
writer = csv.writer(outfile, delimiter=',')
for row in reader:
colad = row[5].rstrip('0123456789./ ')
if colad == row[5]:
col2ad = row[11]
else:
col2ad = row[5].split(' ')[-1]
writer.writerow([row[0],colad,col2ad] +row[1:])
我正在处理一个巨大的 csv 文件,所以想去掉那些多余的行。
我在 Windows 上遇到了同样的问题(我想你的 OS 也是?)。 CSV 和 Windows 作为组合在每行的末尾创建一个 \r\r\n
(因此:双换行符)。
您需要以二进制模式打开输出文件:
with open('test_out.csv', 'wb') as outfile:
其他答案:
Python's CSV writer produces wrong line terminator
CSV in Python adding an extra carriage return
我正在尝试在处理输入的 csv 文件后在 csv 文件中添加额外的列。但是,我在输出的每一行之后添加了额外的新行。
我下面的代码中遗漏或错误的地方 -
import csv
with open('test.csv', 'r') as infile:
with open('test_out.csv', 'w') as outfile:
reader = csv.reader(infile, delimiter=',')
writer = csv.writer(outfile, delimiter=',')
for row in reader:
colad = row[5].rstrip('0123456789./ ')
if colad == row[5]:
col2ad = row[11]
else:
col2ad = row[5].split(' ')[-1]
writer.writerow([row[0],colad,col2ad] +row[1:])
我正在处理一个巨大的 csv 文件,所以想去掉那些多余的行。
我在 Windows 上遇到了同样的问题(我想你的 OS 也是?)。 CSV 和 Windows 作为组合在每行的末尾创建一个 \r\r\n
(因此:双换行符)。
您需要以二进制模式打开输出文件:
with open('test_out.csv', 'wb') as outfile:
其他答案:
Python's CSV writer produces wrong line terminator
CSV in Python adding an extra carriage return