合并CSV文件时出现问题

时间:2019-07-02 23:23:35

标签: python csv

我正在为一个项目组合CSV文件,但无法使第二个脚本正常工作。我使用以下代码合并了第一组文件,效果很好:

import os
import glob
os.chdir(r"C:\Users\maria\Desktop\Project\TRI\Alabama TRI")
fout=open("out.csv","a")
for line in open("Alabama1988.csv"):
    fout.write("Alabama  "+str("1988")+"  "+line)    
for num in range(1989,2018):
    f = open("Alabama"+str(num)+".csv")
    f.__next__() 
    for line in f:
         fout.write("Alabama  "+str(num)+str("  ")+line)
    f.close()
fout.close()

这是我的第二个,由于某种原因,它根本无法工作:

import os
import glob
os.chdir(r"C:\Users\maria\Desktop\Project\TRI\CombinedStates")
fout=open("out.csv","a")
for line in open("Alabama.csv"):
    fout.write(line)
statelist = ["Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"]
for state in statelist:
    f = open(str(state)+".csv")
    f.__next__()
    for line in f:
         fout.write(line)
    f.close()
fout.close()

我检查以确保所有拼写和内容在代码和文件名中均正确无误,此外,我确保所有文件的格式均相同,但是我仍然无法使其正常工作。我想知道我是否可能在第二个代码中犯了一些明显的错误,或者其他人有什么想法。该代码未返回任何错误消息,并且在我运行它时似乎正在运行,但是未创建out.csv文件。谢谢!

1 个答案:

答案 0 :(得分:0)

如果目的是合并这两个csv文件,并且它们完全匹配,请使用熊猫

import pandas as pd
import os
os.chdir(r"C:\Users\maria\Desktop\Project\TRI\Alabama TRI")

df1 = pd.read_csv('Alabama1988.csv')

os.chdir(r"C:\Users\maria\Desktop\Project\TRI\CombinedStates")

df2 = pd.read_csv('Alabama.csv')

df3 = pd.concat([df1, df2])

os.chdir(r"C:\Users\maria\Desktop")

df3.to_csv('Alambama.csv')