所以我试图将两个不同的csv文件合并为一个,我已经做到了。这两个csv文件是在学校的学生,他们在1中存在而在另一个中没有
我需要将创建文件的日期放在新csv的顶部,并将当前学生的每个等级放在新页面上或3行空白之后。
此外,在每个新页面上或每3个空白后,我想要有名称或教师,创建文件的日期和成绩。
import csv
with open('inschool.csv', encoding="cp437") as f:
reader = csv.reader(f)
in_school = list(reader)
with open('notinschool.csv', encoding="cp437") as f:
reader = csv.reader(f)
not_in_school = list(reader)
for grade, name, status, hr_teacher in not_in_school:
print(grade, name, status, hr_teacher)
for grade, name, status, hr_teacher in in_school:
print(grade, name, status, hr_teacher)
iFile = open('inschool.csv', encoding="cp437")
reader = csv.reader(iFile)
IFILE = open('notinschool.csv', encoding="cp437")
READER = csv.reader(IFILE)
oFile = open('combined.csv','wt',encoding="cp437")
writer = csv.writer(oFile, delimiter='|', quoting=csv.QUOTE_ALL)
for row in READER:
writer.writerow(row)
writer.writerow("[]")
for row in reader:
writer.writerow(row)
writer.writerow("[]")
我为3个空白行尝试的代码有这个结尾,但在每个学生姓名之后,而不是在每个年级之后,它给出了3个空行/行。
iFile = open('Inschool.csv',)
reader = csv.reader(iFile)
IFILE = open('notinschool.csv')
READER = csv.reader(IFILE)
oFile = open('combined.csv','wb')
writer_a = csv.writer(oFile, delimiter='|', quoting=csv.QUOTE_ALL)
writer_b = csv.writer(oFile, delimiter='|', quoting=csv.QUOTE_ALL, lineterminator="\n\n\n\n")
for row in READER:
writer_a.writerow(row)
writer_b.writerow([])
for row in reader:
writer_b.writerow(row)
如果有人可以帮助我,我将不胜感激。感谢。
答案 0 :(得分:1)
你可以在终端上轻松完成。只需cd
到目录并执行命令cat inschool.csv notinschool.csv > combined.csv
如果你想在Python
中这样做,我会这样做:
in_file1 = open("inschool.csv","r").read().split("\n")
in_file2 = open("notinschool.csv","r").read().split("\n")
out_file = open("combined.csv","w")
for line in in_file1:
if line:
out_file.write(line + "\n")
for line in in_file2:
if line:
out_file.write(line + "\n")
以上述方式阅读文件并不是最有效的,但如果它们很小,那么它并不重要,并且可以更容易地看到发生了什么。您可以使用此b / c的输入文件方法,概念保持不变:)
我刚开始使用这个名为pandas
的模块,它适用于DataFrames
。它们比解析文本文件更容易使用,处理,导航和合并。