我想通过使用python pandas模块合并许多.text文件。
代码如下所示:

import os
import pandas as pd
root='D:\daymet'
newfile=pd.DataFrame()            #all txt data will append on this variable
for file in os.listdir(root):
    if 'txt' in file:
        pathname=os.path.join(root,file)    #file path
    temp=pd.read_csv(pathname)                # read csv
    newfile.append(temp,ignore_index=True)      #append
newfile.to_csv('D:\\merge.csv')                 #save as a newfile

报告以下错误:
EmptyDataError                            Traceback (most recent call last)
<ipython-input-9-4282b0cc482a> in <module>()
      6     if 'txt' in file:
      7         pathname=os.path.join(root,file)
----> 8     temp=pd.read_csv(pathname)
      9     newfile.append(temp,ignore_index=True)
     10 newfile.to_csv('D:\\merge.csv')

......
pandas\parser.pyx in pandas.parser.TextReader.__cinit__ (pandas\parser.c:6162)()

EmptyDataError: No columns to parse from file

最佳答案

您错过了8和9行中的制表符(您的文件没有'txt',并尝试在不定义路径的情况下打开它)。

import os
import pandas as pd
root='D:\daymet'
newfile=pd.DataFrame()            #all txt data will append on this variable
for file in os.listdir(root):
    if 'txt' in file:
        pathname=os.path.join(root,file)  #file path <--add additional tab here
        temp=pd.read_csv(pathname)  # read csv <--add additional tab here
        newfile.append(temp,ignore_index=True)      #append
newfile.to_csv('D:\\merge.csv')                 #save as a newfile

10-08 05:05