文件处理练习

习题1读一个文件,包含英文句子,请统计共多少个不重复的单词,并且在另外一个文件中打印每个单词以及它的出线次数

result = []
tmp = “”
with open(“c:\code\test\a.txt”, “r”) as f:
for line in f:
for i in line.strip("\n"):
if i.isalpha() == False and tmp != “”:
result.append(tmp)
tmp = “”
else:
tmp += i
print(result)

data = []
for i in result:
if i not in data:
data.append(i)
data.append(result.count(i))

data = str(data).strip("[")
data = str(data).strip("]")

with open(“c:\code\test\word.txt”, “w+”) as f1:
f1.write(str(data))

a.txt文件:
this is a man,man are thing!
today is a good day!
you are a good man!

word.txt文件:
‘this’, 1, ‘is’, 2, ‘a’, 3, ‘man’, 3, ‘are’, 2, ‘thing’, 1, ‘today’, 1, ‘good’, 2, ‘day’, 1, ‘you’, 1

吴老师代码:
#第一步:读文件
#方法1:open
#方法2:with

import string
with open(“e://a.txt”,“r”) as fp:
content = “”
for line in fp:
s = line
for i in string.punctuation:
s=s.replace(i," ")
content += s

print (content)

word_list = content.split()
print(word_list)
print(“一共%s个不重复的单词:” %len(set(word_list)))
word_count = {}
for i in word_list:
if i in word_count:
word_count[i]+=1
else:
word_count[i]=1

print (word_count)

with open(“e://b.txt”,“w”) as fp:
fp.write(“一共%s个不重复的单词:” %len(set(word_list))+"\n")
for key,value in word_count.items():
fp.write("%s单词出现了%s次" %(key,str(value))+"\n")

#难点1:怎么把英文句子中的所有标点去掉。
#数字也要替换掉。

习题2,写个记账程序,每天收入多少,支出多少,总额剩多少,使用序列化方式保存信息

with open(“c:\code\test\count.txt”,“r”) as f:
init_data=f.readlines()
c=int(init_data[-1])

a=int(input(“请输入今天的收入:”))
b=int(input(“请输入今天的支出:”))

c=c+a-b

with open(“c:\code\test\count.txt”,“w+”) as f1:
f1.write(str(a)+"\n")
f1.write(str(b)+"\n")
f1.write(str©+"\n")

吴老师序列化代码实现:
#写个记账程序,每天收入多少,支出多少,
#总额剩多少,使用序列化方式保存信息

import pickle

fp = open(“e:\a.txt”,“rb”)
try:
income=pickle.load(fp)
spend=pickle.load(fp)
deposit=pickle.load(fp)
except:
income = []
spend = []
deposit= 0
fp.close()

#value|specification
while 1:
content = input(“请输入指令:”)
if content.find(“exit”)!=-1:
break

if content.find("|")==-1:   #"|"方便对输入的钱做处理
    print("data format is value|specification")
    print("please input again!")
    continue

value = content.split("|")[0]
try:
    value=float(value)
except:
    print("data format is value|specification")
    print("data format is value must be a number")

if value> 0:
    income.append(content)
    deposit+=value
elif value==0:
    print("空间有限,不存0")
else:
    spend.append(content[1:])
    deposit+=value

print (income)
print (spend)
print (deposit)

fp = open(“e:\a.txt”,“wb”)
pickle.dump(income,fp)
pickle.dump(spend,fp)
pickle.dump(deposit,fp)

fp.close()

练习:
每行内容需要生成以每行首年月日为名称的文件,文件内容写入|0|后的所有行内容(也包括|0| )

数据文件如下:
20160215000148|0|collect info job start|success|
20160215000153|0|collect info job end|success|resultcode = 0000
20160216000120|0|collect info job start|success|
20160216000121|0|collect info job end|success|resultcode = 0000
20160217000139|0|collect info job start|success|
20160217000143|0|collect info job end|success|resultcode = 0000

代码:
#coding:utf-8
fp = open(r’C:\code\yan9.txt’)
fn = “”
data=""
fpath=""
for item in fp:
fn=item[0:14]
data=item[14::]
fpath=‘C:\code\’+fn+’.txt’
fp2 = open(fpath,‘w+’,encoding = “utf-8”)
fp2.write(data)
fp2.close()

fp.close()

执行结果:
一共生成了6个文件,分别为:

20160215000148.txt 内容为:|0|collect info job start|success|
20160215000153.txt 内容为:|0|collect info job end|success|resultcode = 0000
20160216000120.txt 内容为:|0|collect info job start|success|
20160216000121.txt 内容为:|0|collect info job end|success|resultcode = 0000
20160217000139.txt 内容为:|0|collect info job start|success|
20160217000143.txt 内容为:|0|collect info job end|success|resultcode = 0000

吴老师代码:
with open(“e:\a.txt”,encoding=“utf-8”) as fp:
for line in fp:
print (line)
file_name = line.split("|",1)[0]
file_content = line.split("|",1)[1]
with open(“e:\test\”+file_name+".txt",“w”) as fp1:
fp1.write("|"+file_content+"\n")

目录操作:

import os
os.getcwd()
‘C:\Users\admin’

import os
os.getcwd()
‘C:\Users\admin’

os.curdir
‘.’

os.pardir
‘…’

os.chdir(os.pardir)
os.getcwd()
‘C:\Users’

import os .path
os.path.isdir(“subprocesstest”) #判断是不是目录
True

os.path.isfile(“subprocesstest”) #判断是不是文件
False

os.path.exists(“e:\a.txt”) #判断路径是不是存在

os.name #操作系统名称
‘nt’

os.linesep #换行符
‘\r\n’

os.pathsep #路径分隔符
‘;’

os.sep #目录分隔符
‘\’

os.listdir()
[‘a.txt’, ‘a.txt.bak’, ‘b.txt’, ‘count.txt’, ‘count.txt.bak’, ‘test.txt’, ‘u=362335503,1507335222&fm=26&gp=0_xx.jpg’, ‘u=3883729263,605988563&fm=26&gp=0_xx.jpg’, ‘vivian1.txt’, ‘word.txt’, ‘下载_xx.jpg’]

os.mkdir(“yan”) #创建目录
os.makedirs(“yan/test/yan”) #创建多级目录
os.chdir(“yan/test/yan”)
os.getcwd()
‘c:\code\test\yan\test\yan’

os.chdir(“yan/test/yan”)
os.getcwd()
‘c:\code\test\yan\test\yan’

os.chdir(‘c:\code\test\’)
os.listdir()
[‘a.txt’, ‘a.txt.bak’, ‘b.txt’, ‘count.txt’, ‘count.txt.bak’, ‘test.txt’, ‘u=362335503,1507335222&fm=26&gp=0_xx.jpg’, ‘u=3883729263,605988563&fm=26&gp=0_xx.jpg’, ‘vivian1.txt’, ‘word.txt’, ‘yan’, ‘下载_xx.jpg’]

os.removedirs(‘c:\code\test\yan\test\yan’) #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依次类推。

os.remove(filePath) 删除一个指定的文件,参数filePath表示文件所在的路径。

删除目录下的.txt文件
import os
path=“c:\code\test\”
data=os.listdir(path)
for i in data:
if “.txt”==i[-4:]:
filepath=path+i
os.remove(filepath)

算法:
取出某个目录内,1小时内新建的所有文件名。

算法:遍历这个目录,取到所有的文件
每个文件用stat取到创建时间
用创建时间和当前时间去比对,是否小于3600
放到一个列表里面

import os
import time
path=“c:\code\test\”
data=os.listdir(path)
print(data)
result=[]
for i in data:
if (time.time() - os.stat(path+i).st_ctime <=3600) and os.path.isfile(path+i):
filepath=path+i
result.append(i)

print(result)

执行结果:
[‘test’, ‘新建文本文档 (2).txt’, ‘新建文本文档.txt’]
[‘新建文本文档 (2).txt’, ‘新建文本文档.txt’]

#encoding=utf-8
import os

os.utime(r’e:\b.txt’,(1375448978,1369735977)) #修改更改时间
fileinfo = os.stat(r’e:\b.txt’)
print (“access time of b.txt : %s \n modified time of b.txt: %s” % (fileinfo.st_atime,fileinfo.st_mtime))

os.system(“ls”) #os.system()可以用来处理Linux下的命令
os.environ #获取系统环境变量。

os.environ[‘ALLUSERSPROFILE’]
‘C:\ProgramData’

os.popen(command [, mode=‘r’ [, bufsize]])
运行shell命令,并返回一个文件对象。然后通过操作文件的方法去操作这个
文件对象。

for i in os.popen(“ls”):
… print(i)

注意:
Python调用Shell,有两种方法:os.system(cmd)或os.popen(cmd)脚本执行过程中的输出内容。实际使用时视需求情况而选择。
两者的区别是:
os.system(cmd)的返回值是脚本的退出状态码,只会有0(成功),1,2
os.popen(cmd)返回脚本执行的输出内容作为返回值

import os.path
os.path.join(“c:\”,“test”) #自动拼接成路径
‘c:\test’

os.path.join(“c:\code”,“c:\code\yan”)
‘c:\code\yan’

os.path.join(“code”,“test”)
‘code\test’

#encoding=utf-8
import os
dir_count=0
file_count=0
for root, dirs, files in os.walk(“c:\code\test”,topdown=True) : #选择了首先返回目录树下的文件,然后遍历目录树下的子目录
print(‘当前目录:’,root) #打印目录绝对路径
for name in dirs :
dir_count+=1
print(‘目录名:’,name) #打印目录绝对路径
for name in files :
file_count+=1
print(‘文件名:’,os.path.join(root,name) )#打印文件绝对路径

print(“目录个数:%d”%dir_count)
print(“文件个数:%d”%file_count)

执行结果:
当前目录: c:\code\test
目录名: test
文件名: c:\code\test\新建文本文档 (2).txt
文件名: c:\code\test\新建文本文档.txt
当前目录: c:\code\test\test
目录名: test3
文件名: c:\code\test\test\test3.txt
当前目录: c:\code\test\test\test3
文件名: c:\code\test\test\test3\test4.txt
目录个数:2
文件个数:4

小练习,把所有的txt文件干掉。
新建一个空的子目录xxx,放在某个层级下,,把它删掉

#encoding=utf-8
import os
for root, dirs, files in os.walk(“c:\code\test”,topdown=True) :
print(‘当前目录:’,root) #打印目录绝对路径
for name in dirs :
if name==“xxx”:
os.removedirs(os.path.join(root,name))
for name in files :
if name[-4:]==".txt":
os.remove(os.path.join(root,name))

统计代码:
#encoding=utf-8
import os
count=0
for root, dirs, files in os.walk(“C:\Users\admin\Desktop\颜金凤\学习日报\10月”,topdown=True) :
print(‘当前目录:’,root) #打印目录绝对路径
for name in dirs :
print(os.path.join(root,name))
for name in files :
with open(os.path.join(root,name),‘r’) as f:
for line in f:
print(line)
if line.strip()!="" and (line.strip()[0]).isalpha():
count+=1
print(count)

import os.path
os.path.abspath(“test.txt”) #返回path规范化的绝对路径(但这个路径不一定是真实存在的路径)
‘c:\code\test.txt’

os.chdir(“test”)
os.path.abspath(“test.txt”)
‘c:\code\test\test.txt’

生成一个绝对路径函数
#encoding=utf-8
import os
import os.path

def get_dir_abs_path(dir_path):
result = []
for i in os.listdir(dir_path):
result.append(os.path.join(dir_path,i))
return result

print (get_dir_abs_path(“e:\testdemo”))

生成多个文件和目录的绝对路径函数
#encoding=utf-8
import os
import os.path

def get_dir_abs_dirpath(dir_path):
result = []
for root,dirs,files in os.walk(dir_path):
for i in dirs:
result.append(os.path.join(root,i))
return result

def get_dir_abs_filepath(dir_path):
result = []
for root,dirs,files in os.walk(dir_path):
for i in files:
result.append(os.path.join(root,i))
return result

print (get_dir_abs_dirpath(“e:\testdemo”))
print (get_dir_abs_filepath(“e:\testdemo”))

os.path.split(“e:\test\test\a.py”)
(‘e:\test\test’, ‘a.py’)

os.path.dirname(“e:\test\test\a.py”)
‘e:\test\test’

os.path.basename(“e:\test\test\a.py”)
a.py

os.path.splitext(“e:\test\test\a.py”)
(‘e:\test\test\a’, ‘.py’)

#统计一下某个目录下的,所有不同后缀名的个数,
#以及哪些具体的后缀名

#encoding=utf-8
import os
result=[]
for root, dirs, files in os.walk(“c:\code”,topdown=True) :
print(‘当前目录:’,root) #打印目录绝对路径
for name in files :
if os.path.splitext(name)[1] not in result: #获取后置名
result.append(os.path.splitext(name)[1])

print(len(result),result)

执行结果:
6 [’.txt’, ‘.bak’, ‘.data’, ‘.py’, ‘.pyc’, ‘.log’]

if not os.path.exists(“e:\b.txt”): #判断文件在不在
… with open(“e:\b.txt”,“w”):
… pass

os.path.isabs(“e:\text”) #判断是不是绝对路径
True

os.path.normpath(“e://a.txt”) #将path转换成规范的文件路径
‘e:\a.txt’

#coding=utf-8
import os
import time
#获取文件最后访问时间
lastTime = os.path.getatime(r"d:\gloryroad\a.py")
print (lastTime)
#将时间戳转成时间元组
formatTime = time.localtime(lastTime)
print (formatTime)
#格式化时间元组为时间字符串
print (time.strftime("%Y-%m-%d %H:%M:%S", formatTime))

a.py代码
#coding=utf-8

import sys

print (sys.argv)

def add(a,b):
return a+b

print (add(float(sys.argv[1]),float(sys.argv[2])))

执行文件:
C:\code\test>py -3 a.py 10 0.5 #通过命令行来传入参数
[‘a.py’, ‘10’, ‘0.5’]
10.5

C:\code\test>

b.py文件
#coding=utf-8
import sys

print (sys.argv)

def add(a,b):
return a+b

if not len(sys.argv) ==3 :
print(“参数数量不对!请指定两个数字参数”)
sys.exit()
try:
float(sys.argv[1])
float(sys.argv[2])
except:
print(“参数类型不对!请指定两个数字参数”)
sys.exit()

print (add(float(sys.argv[1]),float(sys.argv[2])))

执行:
C:\code\test>py -3 b.py 10
[‘b.py’, ‘10’]
参数数量不对!请指定两个数字参数

C:\code\test>py -3 b.py 10 10 10
[‘b.py’, ‘10’, ‘10’, ‘10’]
参数数量不对!请指定两个数字参数

C:\code\test>py -3 b.py 10 a
[‘b.py’, ‘10’, ‘a’]
参数类型不对!请指定两个数字参数

C:\code\test>py -3 b.py 10 0.5
[‘b.py’, ‘10’, ‘0.5’]
10.5

C:\code\test>

c.py
#coding=utf-8
import os
import sys

def readfile(filename):
‘’‘Print a file to the standard output.’’’
f = open(filename,encoding=“utf-8”)
while True:
line = f.readline()
if len(line) == 0:
break
print (line,)
f.close()

if len(sys.argv) < 3:
print (‘No action specified.’)
sys.exit()

print (“sys.argv[0]---------”,sys.argv[0])
print (“sys.argv[1]---------”,sys.argv[1])
print (“sys.argv[2]---------”,sys.argv[2])

Script starts from here

if sys.argv[1].startswith(’–’):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == ‘version’:
print(‘Version 1.2’)
elif option == ‘help’:
print(’’’"
This program prints files to the standard output.
Any number of files can be specified.
Options include:
–version : Prints the version number
–help : Display this help’’’)
else:
print(‘Unknown option.’)
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)

执行:
C:\code\test>py -3 c.py --version
No action specified.

C:\code\test>py -3 c.py --version --version --version
sys.argv[0]--------- c.py
sys.argv[1]--------- --version
sys.argv[2]--------- --version
Version 1.2

C:\code\test>py -3 c.py --version version
sys.argv[0]--------- c.py
sys.argv[1]--------- --version
sys.argv[2]--------- version
Version 1.2

C:\code\test>

for id ,i in enumerate(range(10,20)):
… print(id,i)

d.py 文件:
#coding=utf-8
import os
import sys

def readfile(filename):
‘’‘Print a file to the standard output.’’’
f = open(filename,encoding=“utf-8”)
while True:
line = f.readline()
if len(line) == 0:
break
print (line,)
f.close()

if len(sys.argv) ==2 and sys.argv[1].startswith(’–’):
pass
elif len(sys.argv) ❤️:
print (‘No action specified.’)
sys.exit()

for id,i in enumerate(sys.argv):
print (“第%s个参数:%s” %(id,i))

Script starts from here

if sys.argv[1].startswith(’–’):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == ‘version’:
print(‘Version 1.2’)
elif option == ‘help’:
print(’’’"
This program prints files to the standard output.
Any number of files can be specified.
Options include:
–version : Prints the version number
–help : Display this help’’’)
else:
print(‘Unknown option.’)
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)

执行:
C:\code\test>
C:\code\test>
C:\code\test>py -3 d.py --version version
第0个参数:d.py
第1个参数:–version
第2个参数:version
Version 1.2

C:\code\test>py -3 d.py --version
第0个参数:d.py
第1个参数:–version
Version 1.2

C:\code\test>py -3 d.py --version 12
第0个参数:d.py
第1个参数:–version
第2个参数:12
Version 1.2

C:\code\test>

id = 10
for i in range(10):
… print (id,i)
… id+=2

作业:写一个代码统计工具

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值