1、读取一个文件,显示除了以#号开头的行以外的所有行。
f=open('2017级-学生信息-1.txt','r')
while 1:
content=f.readlines()
for i in content:
if (i[0] == '#'):
continue
else:
print(i)
break
f.close()
运行结果:
2、已知文本文件中存放了若干数字,请编写程序读取所有数字,排序以后进行输出。
f=open('number.txt','r')
total=f.read()
print(total)
number=[]
for i in total:
number.append(i)
number.sort()
print(number)
f.close()
遇到的问题:如何识别10以外的数字,如果文本里有空格和换行,如何删除。
运行结果:
3、打开一个英文的文本文件,将该文件中的每个字母加密后写入到一个新文件,加密的方法是:将A变成B , B变成C, … Y变成Z , Z变成A ; a变成b,b变成…z变成a , 其他字符不变化。
f=open('English.txt','r')
content = f.read()
newStr = ""
for string in content:
temp = ord(string)#ord返回对应的ASCII值
if temp in range(65,91):
if temp == 90:
char1 = chr(temp-25)#chr当前整数对应的ASCII字符
newStr += char1
else:
char2 = chr(temp+1)
newStr += char2
elif temp in range(97,123):
if temp == 122:
char3 = chr(temp-25)
newStr += char3
else:
char4 = chr(temp + 1)
newStr += char4
else:
newStr = newStr+string
f.close()
f2 = open("English加密后.txt","w")
f2.write(newStr)
f2.close()
运行结果:
4、打开一个英文文本文件,将其中大写字母变成小写,小写字母变成大写。
f=open('English.txt','r')
content=f.read()
content=content.swapcase()#swapcase() 方法用于对字符串的大小写字母进行转换
print(content)
f=open('English.txt','w')
f.write(content)
f.close()
运行结果:
5、在日常生活中,经常会遇到某些需求对文件名称进行修改,借助刚学过的文件操作,编写一个可以批量修改文件名的小程序
import os
files=os.listdir("./")
#print(files)
i=0
for file in files:
fileFormat=files[i][files[i].find("."):]
#print(fileFormat)
fileName=files[i][:files[i].find(".")]
fileName.strip()
#print(fileName)
if(fileFormat.strip() == ".txt".strip()):
os.rename(fileName+fileFormat,"2017-学生信息-"+str(i+1)+fileFormat)
i=i+1