所以我写了一个格式化文本文件的python脚本,这样我就可以导入到我的SQL中。我使用python 3.5,我的代码完美工作。换行符不能用python 2.7
但是,当我尝试在python 2.7中运行我的代码时,它不起作用,它会引发此错误。 (我必须使用2.7)直到后来我才知道这一点。
TypeError: 'newline' is an invalid keyword argument for this function.
有没有解决的办法,如果我不使用换行符,它跳过行我的数据,并将其显示为一个空白行。
这里是我的代码:
import csv
import os
my_file_name = os.path.abspath('NVG.txt')
cleaned_file = "cleanNVG.csv"
BulkImport_file = 'BulkImport.txt'
remove_words = ['INAC-EIM','-INAC','TO-INAC','TO_INAC','SHIP_TO-inac','SHIP_TOINAC']
with open(my_file_name, 'r', newline='') as infile, open(cleaned_file, 'w',newline='') as outfile:
writer = csv.writer(outfile)
cr = csv.reader(infile, delimiter='|')
writer.writerow(next(cr)[:25])
for line in (r[0:25] for r in cr):
if not any(remove_word in element for element in line for remove_word in remove_words):
line[11]= line[11][:5]
writer.writerow(line)
infile.close()
outfile.close()
with open(cleaned_file, 'r') as fin, open(BulkImport_file, 'w') as fout:
reader = csv.DictReader(fin)
writer = csv.DictWriter(fout, reader.fieldnames, delimiter='|')
writer.writeheader()
writer.writerows(reader)
如何修改我的代码,所以它与Python 2.7兼容。非常感谢!
python 2.7中没有'newline'参数''open'' – Arman
python 2.7有没有类似于newline的参数? – Cesar
[Python 3.5 Open function doc](https://docs.python.org/3/library/functions.html#open) – Arman