我正在尝试使用Python将行从一个csv文件复制到另一个csw文件,并在此过程中将数据添加到新列。数据被正确地复制到新文件中,但所有数据都被复制到了新文件中的同一行。
file = "C:/original_file.csv"
nf = "C:/file_updated.csv"
i = 0
with open(file, 'r') as origFile:
with open(nf, 'w') as newFile:
lineList = []
for line in origFile:
strippedLine = line.strip()
lineList = strippedLine.split(',')
lineList.append("C:/ATT" + str(i) + "_PHOTO 1.jpg")
lineStr = str(lineList)
lineStr = lineStr.replace("'", "")
newFile.write(lineStr)
print lineList
i += 1
origFile.close()
newFile.close()
如何使第一个文件中的每一行都复制到新文件的一行?
file = "C:/original_file.csv"
nf = "C:/file_updated.csv"
i = 0
with open(file, 'r') as origFile:
with open(nf, 'w') as newFile:
lineList = []
for line in origFile:
strippedLine = line.strip()
lineList = strippedLine.split(',')
lineList.append("C:/ATT" + str(i) + "_PHOTO 1.jpg")
lineStr = str(lineList)
lineStr = lineStr.replace("'", "")
newFile.write(lineStr)
newFile.write('n') #Insert a new line
print lineList
i += 1
origFile.close()
newFile.close()
无需安装pandas
,内置的csv
库非常适合!!
$ cat tmp.csv
first,second
third,fourth
import csv
to_read = "./tmp.csv"
to_write = "./tmp2.csv"
with open(to_read, newline="") as to_read_fp, open(to_write, "w", newline="") as to_write_fp:
reader = csv.reader(to_read_fp)
writer = csv.writer(to_write_fp)
for count, row in enumerate(reader):
row.append(f"C:/ATT{count}_PHOTO 1.jpg")
writer.writerow(row)
$ cat tmp2.csv
first,second,C:/ATT0_PHOTO 1.jpg
third,fourth,C:/ATT1_PHOTO 1.jpg
如果您想在不进行任何导入的情况下执行此操作,您可以尝试这样的操作,即添加一个标题为New Field
的新列。
当然,它假设原始CSV有一个标题行。
file = "original_file.csv"
nf = "file_updated.csv"
with open(file, 'r') as origFile:
data = [line.strip().split(',') for line in origFile.readlines()]
header = data[0]
data = data[1:]
header.append('New Field')
data = [line + [f'C:/ATT{idx}_PHOTO 1.jpg'] for idx, line in enumerate(data)]
data = [','.join(line) for line in [header]+data]
with open(nf, 'w') as newFile:
newFile.writelines('n'.join(data))
"""
SAMPLE INPUT
Field1,Field2
Data1,Data2
Data3,Data4
SAMPLE OUTPUT
Field1,Field2,New Field
Data1,Data2,C:/ATT0_PHOTO 1.jpg
Data3,Data4,C:/ATT1_PHOTO 1.jpg
"""