python文件处理_批量读取txt文件转换为dataframe并存入csv

批量做Text文本写入csv时,首先把text文件读入dataframe,然后添加左列text路径名为文件名,右列为文章内容。

– coding:utf-8 –
import os
import os.path
import codecs
filePaths=[]
fileContents=[]
for root,dirs,files in os.walk(‘data/output_text’):
for name in files:
filePath=os.path.join(root,name)
filePaths.append(filePath)
f=codecs.open(filePath,’r’,’utf-8′)
f=codecs.open(filePath,’r’)
fileContent=f.read()
f.close()
fileContents.append(fileContent)

import pandas
df=pandas.DataFrame({
‘filePath’:filePaths,
‘fileContent’:fileContents
})
df[‘filePath’] = df[‘filePath’].str[17:21] #添加左列text路径名为文件名

df.to_csv(‘data/df.csv’,encoding = ‘utf-8’) #存入csv

Original: https://blog.csdn.net/weixin_51533158/article/details/118353355
Author: Kiko_slly
Title: python文件处理_批量读取txt文件转换为dataframe并存入csv

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/677253/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球