首页 > 解决方案 > 读取,将 .xlsx 文件转换为 csv 和连接

问题描述

因此,我编写了一个代码,它成功地逐个读取目录中的所有 .xls 文件,然后将其转换为 csv 格式,最后将它们连接起来,以便程序随后在该单个连接的 csv 文件上运行。

此代码也适用于 .txt,只需将 .xls 替换为 .txt。我认为在 .xlsx 格式的情况下会相似,但我错了。由于某种原因,它显示错误。

代码是:

path="C:\\Users\\AD\\Downloads\\Excess data"  #Change this directory to the location of your directory.
allFiles = glob.glob(path + "\\*.xls")  #Searches for all files with .txt/.xls.

list_ = []
for file in allFiles:
    print(file)
    bytes = open(file, 'rb').read()
    df=pd.read_csv(io.StringIO(bytes.decode('utf-8')), sep='\t', parse_dates=['Time'] )
    list_.append(df)

Source = pd.concat(list_)
Source.head()

此代码为 .xls 和 .txt 成功运行,但在 .xlsx 的情况下,我收到一些错误:

*UTF-8 can't decode ...at position.. something like this*

谢谢您的帮助!

标签: pythonpython-3.xpandas

解决方案


我建议read_excel与列表理解一起使用:

#Change this directory to the location of your directory. 
path="C:\\Users\\AD\\Downloads\\Excess data" 

#Searches for all files with .txt/.xls.
allFiles = glob.glob(path + "\\*.xls")  

list_ = [pd.read_excel(file) for file in allFiles]
Source = pd.concat(list_, ignore_index=True)
print Source

#convert to csv
Source.to_csv('out.csv', index=False)

推荐阅读