python对文件操作的统一步骤_基于Python实现对各种数据文件的操作

本文总结使用Python对常见的数据文件进行读写操作。

注:我这有个学习基地,里面有很多学习资料,感兴趣的+Q群:895817687

常见的数据文件类型如下:

txt

csv

excel(xlsxlsx)

在线网页数据

pdfword

其他数据软件格式

1 txt文件

文件读取

# 文件input

file_txt = os.path.join(workdir,’Data/demo_text.txt’)

# 打开文件

f = open(file_txt, encoding=’utf-8′)

# 将每行的文本读取,并存为列表

# 此处使用.rstrip()去除空格、换行符

lines_raw = [x.rstrip() for x in f]

# 或者

# lines_raw = [l.rstrip() for l in f.readlines()]

print(lines_raw)

# 关闭文件

f.close()

输出如下:

[‘010杜甫:佳人’, ”, ‘绝代有佳人,幽居在空谷。’, ‘自云良家子,零落依草木。’, ‘关中昔丧乱,兄弟遭杀戮。’, ‘官高何足论,不得收骨肉。’, ‘世情恶衰歇,万事随转烛。’, ‘夫婿轻薄儿,新人美如玉。’, ‘合昏尚知时,鸳鸯不独宿。’, ‘但见新人笑,那闻旧人哭!’, ‘在山泉水清,出山泉水浊。’, ‘侍婢卖珠回,牵萝补茅屋。’, ‘摘花不插发,采柏动盈掬。’, ‘天寒翠袖薄,日暮倚修竹。’]

也可以用pandas来读取

df_txt = pd.read_csv(file_txt, names=[‘txt’], encoding=’utf-8′)

df_txt.head()

输出如下:

python对文件操作的统一步骤_基于Python实现对各种数据文件的操作

在这里插入图片描述

也可以把csv当做文本文件来读取,不过处理过程稍微复杂点,尤其是字段内的取值中含有分隔符(比如逗号)时,例如上面的name字段。

3 excel(xlsxlsx)文件在这里插入代码片

pandas工具包中也提供了相应的函数来读写excel文件(pandas.read_excel()和dataframe.to_excel())。

更多参考:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html#pandas.read_excel

不同于csv文件,xlsx文件中会有多个sheet,pandas.read_excel函数默认读取第一个sheet.

# 定义文件路径

file_excel = os.path.join(workdir,’Data/demo_xlsx.xlsx’)

# pandas.read_excel()函数来读取文件

# sheet_name=0表示读取第一个sheet,也可以指定要读取的sheet的名称(字符串格式)

# header=0 表示使用第一行作为表头(列名)

# 如果数据中没有列名(表头),可以设置header=None,同时names参数来指定list格式的列名

df_excel = pd.read_excel(file_excel,sheet_name=0,header=0,encoding=’utf-8′)

# dataframe.to_csv()保存csv文件

df_excel.to_excel(‘out_excel.xlsx’,index=False,encoding=’utf-8′)

# 查看dataframe前3行

df_excel.head(3)

这里用xlwings示范自动化“填表”,比如现在有3个项目对应的3个单元格需要填写。

python对文件操作的统一步骤_基于Python实现对各种数据文件的操作

在这里插入图片描述

import xlwings as xw

file_excel = os.path.join(workdir,’Data/demo_填表.xlsx’)

# 打开excel文件的时候不要展示页面

app = xw.App(visible=False)

# 打开工作簿

wb = xw.Book(file_excel)

# 打开工作表

# 可以用index,可以指定sheet的名称

ws = wb.sheets[0]

# 读取对应单元格的值

print(ws.range(‘A1’).value)

ws.range(‘B1’).value = ‘Ahong’

ws.range(‘B2’).value = ‘男’

ws.range(‘B3’).value = ‘Pyhon’

# 保存工作簿

wb.save()

# 也可以保存为新的文件名,e.g.wb.save(‘new.xlsx’)

# 关闭工作簿

wb.close()

如果要批量从多个统一格式的excel文件中读取多个单元格或者写入数据,不妨考虑此方法。

4 在线网页数据

通常网络爬虫的步骤如下:

分析网页请求规范,比如是get还是post,请求的url是啥,返回的数据是什么格式(json态html,header参数,url或者post中的变量有什么等;

获取网页数据,使用requests包;

解析网页数据(将半结构化的网页数据转化为结构化数据),BeautifulSoup、lxml、re、json齐上阵;

整合数据并存档,使用pandas对数据进行整合并初步清洗。

处理pdf文件时,要注意文件需要是“已解密”或者“无密码”状态,“加密”状态的文件处理时会报错。

pdf解密工具推荐:

http://freemypdf.com/

https://smallpdf.com/unlock-pdf

这里举例说明PyPDF2的用法,筛选奇数页面并保存为新文档。

import PyPDF2

# 读入文件路径

file_in = os.path.join(workdir,’Data/demo_pdf.pdf’)

# 打开要读取的pdf文件

f_in = open(file_in,’rb’)

# 读取pdf文档信息

pdfReader = PyPDF2.PdfFileReader(f_in)

# pdf文件页面数

page_cnt = pdfReader.getNumPages()

pdfWriter = PyPDF2.PdfFileWriter()

# 筛选奇数页面

for page_idx in range(0,page_cnt,2):

page = pdfReader.getPage(page_idx)

pdfWriter.addPage(page)

# 输出文档

file_out = open(‘pdf_out.pdf’, ‘wb’)

pdfWriter.write(file_out)

# 关闭输出的文件

file_out.close()

# 关闭读入的文件

pdf_file.close()

如果要解析pdf文件的页面数据(文件上都写了啥),推荐的工具包为:

安装好pdfminer.six后,直接在命令行中调用如下命令即可:

import textract

# 文件路径

file_pdf = os.path.join(workdir,’Data/demo_pdf.pdf’)

# 提取文本

text_raw = textract.process(file_pdf)

# 转码

text = text_raw.decode(‘utf-8’)

5.2 读取Word文件

6 其他数据软件文件

比如SAS, SPSS,Stata等分析软件导出的数据格式。

可以使用的工具包pyreadstat, https://github.com/Roche/pyreadstat

# 使用Python读取.sav文件

# https://github.com/Roche/pyreadstat

import pyreadstat

# 文件路径

file_data = os.path.join(workdir,’Data/demo_sav.sav’)

# 读取文件

df,meta = pyreadstat.read_sav(file_data)

# df就是转化后的数据框

# 查看编码格式

print(meta.file_encoding)

df.head()

更多参考

https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html

Automate the Boring Stuff with Python: Practical Programming for Total Beginners

附PDF文件转字符串的函数

—————————————————–

注:我这有个学习基地,里面有很多学习资料,感兴趣的+Q群:895817687

—————————————————–

# ref: https://stackoverflow.com/questions/26494211/extracting-text-from-a-pdf-file-using-pdfminer-in-python

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter

from pdfminer.converter import TextConverter

from pdfminer.layout import LAParams

from pdfminer.pdfpage import PDFPage

from io import StringIO

def convert_pdf_to_txt(path):

rsrcmgr = PDFResourceManager()

retstr = StringIO()

codec = ‘utf-8’

laparams = LAParams()

device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)

fp = open(path, ‘rb’)

interpreter = PDFPageInterpreter(rsrcmgr, device)

password = “”

maxpages = 0

caching = True

pagenos=set()

for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):

interpreter.process_page(page)

text = retstr.getvalue()

fp.close()

device.close()

retstr.close()

return text

如果喜欢看小编的文章记得关注走一波,另外小编是一名python开发工程师,这里有我自己整理了一套最新的python系统学习教程,包括从基础的python脚本到web开发、爬虫、数据分析、数据可视化、机器学习等。想要这些资料的可以关注小编,并在后台私信小编:“01”即可领取。

文章知识点与官方知识档案匹配,可进一步学习相关知识Python入门技能树进阶语法文件209413 人正在系统学习中 相关资源:翠雨方工作备忘录工具v2.31中文绿色版-其它代码类资源-CSDN文库

来源:weixin_39528697

声明:本站部分文章及图片转载于互联网,内容版权归原作者所有,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2020年11月2日
下一篇 2020年11月2日

相关推荐