读取.xlsx文件,将其转换为csv文件并连接

2024-03-28 20:52:55 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我写了一个代码,成功地一个接一个地读取目录中的所有.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*

谢谢你的帮助!你知道吗


Tags: 文件csvpath代码txt格式错误this
1条回答
网友
1楼 · 发布于 2024-03-28 20:52:55

我建议将^{}与列表理解结合使用:

#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)

相关问题 更多 >