文件自动化处理

阅读: 评论:0

文件自动化处理

文件自动化处理

 

1读写文件

当程序运行时,我们可以用变量来保存运算结果,而程序运行关闭后,我们可以将数据保存到文件中。本节学习的重点就是如何使用pyhton在硬盘上创建、读取和保存文件。

1.1 文件与文件路径

文件的两个属性:“路径”和“文件名”,路径指明文件在计算机上的位置,文件名是指该位置的文件的名称。

在windows上,文件夹之间使用反斜杠 '' 作为分隔符。通常我们用`os.path.join()`函数来创建文件名称字符串。

import os
os.path.join('Datawhale\POA', 'douc') # 'Datawhale\POA\douc'

返回的结果是('Datawhale\POA\douc'),看起来文件夹之间的分隔符是双反斜杠,这是因为第一个反斜杠是用来转义的。

1.2 当前工作目录

使用os.getcwd()函数可以获取当前工作目录的字符串,get current working directory。

os.getcwd()# 'F:\Datawhale'

 os.chdir()函数则可以改变当前工作目录,change directory。

os.chdir('F:\Datawhale\POA')
os.getcwd()# 'F:\Datawhale\POA'

1.3 路径操作

1.3.1 绝对路径和相对路径

“绝对路径”,总是从根文件夹开始。

“相对路径”,相对于程序的当前工作目录。

相对路径中,单个句点“.”表示当前目录的缩写,两个句点“..”表示父文件夹。

将相对路径转换为绝对路径,返回绝对路径的字符串, absolute path。

os.path.abspath('.')# 'F:\Datawhale\POA'

判断是否为绝对路径,返回False,is absolute?

os.path.isabs('.')# Falseos.path.isabs(os.path.abspath('.'))  # True

1.3.2 路径操作

lpath('path', 'start'):返回开始路径到path的相对路径的字符串。

lpath(''F:\Datawhale\POA', 'F:\')# 'Datawhale\POA'

如未指定start,则当前工作目录为start。

lpath('F:\Datawhale\POA')
# '.'

os.path.dirname(path): 返回当前路径的目录名。

filePath = 'F:DatawhalePOA\result.csv'
os.path.dirname(filePath)# 'F:\Datawhale\POA'

os.path.basename(path):返回当前路径的文件名。

os.path.basename(filePath)# 'result.csv'

os.path.split():返回一个存放路径目录名dirname和文件名basename 两个字符串的元组。

os.path.split(filePath)# ('F:\Datawhale\POA', 'result.csv')

或者可以同时调用os.path.dirname()和os.path.basename,将他们的返回值放在同一个元组中。

(os.path.dirname(filePath),os.path.basename(filePath)) # ('F:\Datawhale\POA', 'result.csv')

使用split方法,以os.path.sep(路径分隔符)分割路径为每个文件夹的字符串,存放在列表中。

filePath.split(os.path.sep)# ['F:', 'Datawhale', 'POA', 'result.csv']

 

1.3.3 路径有效性检查

ists(path):如果path所指的文件或文件夹存在,返回True,否则False。

path = 'F:\Datawhale\POA'
ists(path)  # True

 os.path.isfile(path):如果path存在,且是一个文件,返回True,否则False。

os.path.isfile(path)  # False

 os.path.isdir(path):如果path存在,且是一个文件夹,返回True,否则False。

os.path.isdir(path)  # True

1.4 文件及文件夹操作

1.4.1 用os.makedirs()创建新文件夹

os.makedirs()可以创建所有必要的中间文件夹。

如果文件夹已存在,不会覆盖已有文件夹,会报错,若不存在,查看目录,已创建。

os.makedirs('F:\Datawhale\POA\practice')

1.4.2 查看文件大小和文件夹内容

返回path中文件的字节数。

size(path)  # 0

 返回包含path中的每个文件名字符串的列表。

os.listdir(path)  # [&#', 'result.csv']

可以同时使用size()和os.listdir(),可以获取目录下的所有文件的总字节数。 

os.path.join() 用于路径拼接文件路径,可以传入多个参数。

totalSize = 0
for filename in os.listdir('./'):totalSize = totalSize + size(os.path.join('./',filename))
print(totalSize)# 11500

1.5 文件读写过程

1.5.1 用open()函数打开文件

调用open()函数返回一个File对象。

helloFile = open('.')
print(helloFile)# <_io.TextIOWrapper name='.\' mode='r' encoding='cp936'>

1.5.2 读取文件内容  

read() 读取文件内容。

helloContent = ad()
helloContent  # 'hello pythonnhello datawhalenhello myteam'

按行读取文件内容,每行内容作为一个以n结尾的字符串写进一个列表当中。

file = open('.')
adlines()# ['hello pythonn', 'hello datawhalen', 'hello myteam']

1.5.3 写入文件

需要用“写模式” 'w' 和 “添加模式” 'a' 打开一个文件,而不能用读模式打开文件。

使用open函数写入文件时,需要在后面加上'w'表明“写模式”,如果没有该文件则会自动创建,若有该文件则会覆盖原有文件。

studyFile = open(&#', 'w') # write
studyFile.write('I'm learning Python Office Automation.n')

需要注意,需要在关闭后才能完成写入。

studyFile.close()

追加写入时,使用“添加模式”在已有文件的末尾添加文本,若是需要换行的添加则应该在上一句的文本末尾自行添加换行符。

studyFile = open(&#', 'a') # append
studyFile.write('I study with my teammates.n')
studyFile.close() 

studyFile = open(&#')
content = ad()
studyFile.close()
print(content)# I'm learning Python Office Automation.
# I study with my teammates.

1.5.4 保存变量

shelve模块可以将变量保存到二进制的shelf文件中,这样可以从硬盘中恢复变量的数据。
在windows上,我们在工作目录里会发现三个新文件:mydata.bak、mydata.dat和mydata.dir。

import shelve
shelfFile = shelve.open('mydata')
cats = ['Zonphie', 'Pooka', 'Simon']
shelfFile['cats'] = cats
shelfFile.close()

需要注意,shelf值不必用读或写模式打开,因为打开后,既能读又能写。

shelfFile = shelve.open('mydata')
type(shelfFile) # shelve.DbfilenameShelf

重新打开这些文件,取出数据。

shelve.DbfilenameShelf  # shelve.DbfilenameShelf
shelfFile['cats']  # ['Zonphie', 'Pooka', 'Simon']
shelfFile.close()

像字典一样,shelf值有keys()和values()方法,返回shelf中键和值的类似列表的值,但不是真正的列表,将它们传递给list()函数,获得列表。

shelfFile = shelve.open('mydata')
list(shelfFile.keys())  # ['cats']
list(shelfFile.values())  # [['Zonphie', 'Pooka', 'Simon']]
shelfFile.close()

pprint.pformat(): 获取该文本字符串,而不是将它打印出来,这个字符串既易于阅读,也是语法上正确的Python代码。

import pprint
cats = [{'name':'Zophie','desc':'chubby'},{'name':'Pooka','desc':'fluffy'}]
pprint.pformat(cats)# "[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"

可以将字符串写入.py文件,以便将来使用,这个文件可以成为我们自己的模块,需要使用其中的变量可以直接导入。

fileObj = open('myCats.py','w')
fileObj.write('cats = '+pprint.pformat(cats)+'n')
fileObj.close()

import语句可以导入Python脚本,我们将cats保存在myCats.py中,自然可以将它作为模块导入。

import myCats
myCats.cats# [{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]myCats.cats[0]# {'desc': 'chubby', 'name': 'Zophie'}myCats.cats[0]['name']# 'Zophie'

1.6 练习

1、如果已有的文件以写模式打开,会发生什么?

将已有的文件以写模式打开,会直接覆盖重写原来的文件。

2、read()和readlines()方法之间的区别是什么?

read()方法将文件内容直接读取成一个字符串,而readlines()则按行读取文件中的内容,每行内容作为一个以n结尾的字符串写进一个列表当中。

综合练习: 一、生成随机的测验试卷文件 假如你是一位地理老师, 班上有 35 名学生, 你希望进行美国各州首府的一个 小测验。不妙的是,班里有几个坏蛋, 你无法确信学生不会作弊。你希望随机调整 问题的次序, 这样每份试卷都是独一无二的, 这让任何人都不能从其他人那里抄袭答案。当然,手工完成这件事又费时又无聊。 好在, 你懂一些 Python。

下面是程序所做的事:

• 创建 35 份不同的测验试卷。

• 为每份试卷创建 50 个多重选择题,次序随机。

• 为每个问题提供一个正确答案和 3 个随机的错误答案,次序随机。

• 将测验试卷写到 35 个文本文件中。

• 将答案写到 35 个文本文件中。

这意味着代码需要做下面的事:

• 将州和它们的首府保存在一个字典中。

• 针对测验文本文件和答案文本文件,调用 open()、 write()和 close()。

• 利用 random.shuffle()随机调整问题和多重选项的次序。

import randomcapitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix','Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado':'Denver','Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida':'Tallahassee','Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho':'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', 'Iowa':'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', 'Louisiana':'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis', 'Massachusetts':'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi':'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska':'Lincoln', 'Nevada': 'Carson City', 'New Hampshire': 'Concord','New Jersey': 'Trenton', 'New Mexico':'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh','North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City','Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence','South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia':'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}# 随机创建35份试卷
for paperNum in range(35):# 创建试卷和答案文本文件paperFile = open('' % (paperNum + 1), 'w')answerFile = open('paper_' % (paperNum + 1), 'w')# 标题和开头paperFile.write('姓名:nn日期:nn班级:nn')paperFile.write('试卷号:%s' % (paperNum + 1))paperFile.write('nnn')# 随机获取capital名称states = list(capitals.keys())random.shuffle(states)  # 打乱states的顺序# 循环states,制造50个问题for questionNum in range(50):# 试卷的正确的选项correctAnswer = capitals[states[questionNum]]# 所有错误选项wrongAnswers = list(capitals.values())del wrongAnswers[wrongAnswers.index(correctAnswer)]  # 删除列表中的正确答案wrongAnswers = random.sample(wrongAnswers, 3)answerOption = wrongAnswers + [correctAnswer]random.shuffle(answerOption)# 在文件中写入问题paperFile.write('%s, %s 的首府是:(  )?n' % (questionNum + 1,states[questionNum]))for i in range(4):paperFile.write(' %s. %sn' % ('ABCD'[i], answerOption[i]))paperFile.write('n')# 在答案卷中写入答案answerFile.write('%s. %sn' % (questionNum + 1, 'ABCD'[answerOption.index(correctAnswer)]))paperFile.close()answerFile.close()

 

2 组织文件

学习了如何使用Python创建并写入新文件,本节重点学习如何用程序组织硬盘上已经存在的文件。

2.1 shutil模块

shutil(或称为shell工具)模块中包含一些函数,可以在Python程序中复制、移动、改名和删除文件。要使用shutil的函数,首先需要import shutil。

2.1.1 复制文件和文件夹

其中destination可以是:

1)、一个文件的名称,则将source文件复制为新名称的destination

2)、一个文件夹,则将source文件复制到destination中

3)、若这个文件夹不存在,则将source目标文件内的内容复制到destination中,若destination文件夹不存在,则自动生成该文件。(慎用,因为会将source文件复制为一个没有扩展名的名字为destination的文件)

将文件复制到已存在的指定目录文件夹。

import shutil
py('F:\Datawhale\POA\', 'F:\Datawhale\POA\practice')# 'F:\Datawhale\POA\practice\'

 将文件复制到指定文件,这里会将文件中的内容覆写进中。

py('F:\Datawhale\POA\', 'F:\Datawhale\POA\practice\')# 'F:\Datawhale\POA\practice\'

 将文件复制到不存在的文件夹,结果将文件复制为一个没有扩展名的名字为exercise的文件。

py('F:\Datawhale\POA\', 'F:\Datawhale\POA\exercise')# 'F:\Datawhale\POA\exercise'

 

destination处的文件夹为新创建的文件夹,如已存在,则会报错。

pytree('F:\Datawhale\POA', 'F:\Datawhale\POA\practice')

 

pytree('F:\Datawhale\POA', 'F:\Datawhale\POA\practice1')

2.1.2 文件和文件夹的移动与改名

1)、如果source和destination是文件夹,且destination已存在,则会将source文件夹下所有内容复制到destination文件夹中。移动。

2)、如果source是文件夹,destination不存在,则会将source文件夹下所有内容复制到destination文件夹中,source原文件夹名称将被替换为destination文件夹名。 移动+重命名

3)、如果source和destination是文件,source处的文件将被移动到destination处的位置,并以destination处的文件名进行命名,移动+重命名。

注意:如果destination中有原来已经存在同名文件,移动后,会被覆写,所以应当特别注意。

ve('F:\Datawhale\POA\practice','F:\Datawhale\POA\docu')# 'F:\Datawhale\POA\docu\practice'
ve('F:\Datawhale\POA\practice1','F:\Datawhale\POA\docue')# 'F:\Datawhale\POA\docue'
ve('F:\Datawhale\POA\','F:\Datawhale\POA\docu\')# 'F:\Datawhale\POA\docu\'

2.1.3 永久删除文件和文件夹

os.chdir('F:\Datawhale\POA\docue')
os.getcwd()# 'F:\Datawhale\POA\docue'
for filename in os.listdir():dswith('.txt'):#删除以.txt结尾的文件#os.unlink(filename)print(filename)# 

2.1.4 用send2trash模块安全地删除

pip install send2trash

import send2trash
send2trash.send2trash(&#')

2.2 遍历目录树

 os.walk(path):传入一个文件夹的路径,在for循环语句中使用os.walk()函数,遍历目录树,和range()函数遍历一个范围的数字类似。不同的是,os.walk()在循环的每次迭代中,返回三个值: 1)、当前文件夹称的字符串。

2)、当前文件夹中子文件夹的字符串的列表。

3)、当前文件夹中文件的字符串的列表。

注:当前文件夹,是指for循环当前迭代的文件夹。程序的当前工作目录,不会因为os.walk()而改变。

for folderName, subFolders, fileNames in os.walk('F:\Datawhale\POA'):print("The current folder is " + folderName)for subFolder in subFolders:print("Subfolder of " + folderName + ':' + subFolder)for fileName in fileNames:print("File inside " + folderName + ':' + fileName)print(' ')

2.3 用zipfile模块压缩文件

 为方便传输,常常将文件打包成.zip格式文件。利用zipfile模块中的函数,Python程序可以创建和打开(或解压)zip文件。

2.3.1 创建和添加到zip文件

import zipfile
newZip = zipfile.ZipFile('new.zip', 'w')
newZip.write(&#', compress_type = zipfile.ZIP_DEFLATED)
newZip.close()
newZip = zipfile.ZipFile('new.zip', 'w')
newZip.write('result.csv', compress_type = zipfile.ZIP_DEFLATED)
newZip.close()
newZip = zipfile.ZipFile('new.zip', 'a')
newZip.write(&#', compress_type = zipfile.ZIP_DEFLATED)
newZip.close()
newZip = zipfile.ZipFile('example.zip', 'w')
for folderName, subFolders, fileNames in os.walk('F:\Datawhale\POA'):for fileName in fileNames:newZip.write(os.path.join(folderName, fileName), compress_type = zipfile.ZIP_DEFLATED)
newZip.close()

2.3.2 读取zip文件

import zipfile, os
exampleZip = zipfile.ZipFile('example.zip')
exampleZip.namelist()
catInfo = info('Datawhale/')
catInfo.file_size
catInfopress_size
print('Compressed file is %s x smaller!' %(round(catInfo.file_size/catInfopress_size, 2)))
exampleZip.close()

2.3.3 从zip文件中解压

import zipfile, os
exampleZip = zipfile.ZipFile('example.zip')
actall('.zip')
exampleZip.close()
exampleZip = zipfile.ZipFile('example.zip')
act('Datawhale/')
act('Datawhale/', 'F:\Datawhale\POA\folders')
exampleZip.close()

2.4 练习

 1)、编写一个程序,遍历一个目录树,查找特定扩展名的文件(诸如.pdf 或.jpg)。不论这些文件的位置在哪里, 将它们拷贝到一个新的文件夹中。

import os
import shutil
path = 'C:\Users\18823\Pictures\Camera Roll'
out_path = 'F:\Datawhale\POA\JPG'
for folderName, subFolders, fileNames in os.walk(path):for file in fileNames:dswith('.jpg'):py(os.path.join(folderName,file), out_path)

 2) 、一些不需要的、 巨大的文件或文件夹占据了硬盘的空间, 这并不少见。如果你试图释放计算机上的空间, 那么删除不想要的巨大文件效果最好。但首先你必须找到它们。编写一个程序, 遍历一个目录树, 查找特别大的文件或文件夹, 比方说, 超过100MB 的文件(回忆一下,要获得文件的大小,可以使用 os 模块的 size())。将这些文件的绝对路径打印到屏幕上。

import os
import shutil
path = 'F:\迅雷下载\进击的巨人\Attack on Titan S2'
for folderName, subFolders, fileNames in os.walk(path):for file in fileNames:filepath = os.path.join(folderName, file)if size(filepath) > 100 * 1024 *1024:print(file + ' : ' + str(int(size(filepath)/1024/1024)) + 'MB')

3)、编写一个程序, 在一个文件夹中, 找到所有带指定前缀的文件, 诸如 , 等,并定位缺失的编号(例如存在 和 , 但不存在 )。让该程序对所有后面的文件改名, 消除缺失的编号。作为附加的挑战,编写另一个程序,在一些连续编号的文件中,空出一些编号,以便加入新的文件。

import os
wd()
os.chdir('F:\Datawhale\POA\docu\spam')filenames = []
for i in range(15):filenames.append('spam'+'%03d'%(i+1)+'.txt')files = random.sample(filenames,10)for filename in files:with open(filename, 'w') as wn:wn.write('          This is '+filename+'          n')

for filename in filenames:if filename not in os.listdir():with open(filename, 'w') as wn:wn.write('          This is missing '+filename+'          n')print(filename)

本文发布于:2024-02-04 20:13:43,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170715592659246.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:文件
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23