python - 读取,将 .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*
谢谢您的帮助!
解决方案
我建议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)
推荐阅读
- vue.js - 在类星体上导入蓝鸟
- google-sheets - 使用 Google QUERY 从其他列返回 MAX 值和相应值
- python - Python - 寻找最佳的单字符通配符组合
- reactjs - 如何在 React js 中使用 jquery ui 滑块
- google-bigquery - 加入条件下的 BigQuery 子查询
- reactjs - 如何在 react-native 中向此按钮添加导航
- python - 球的代码出现错误 - ball = Ball(canvas, paddle, 'red') TypeError: __init__() missing 1 required positional argument: 'color'
- javascript - 函数更新联系人未定义,虽然已定义
- haskell - LYAH - 在链接 Writer monad 时理解关于“tell”的评论
- sql - 用于查找列之间共有值的 SQL 代码