1、批量修改文件名
import os
import sys
path = "E:\作业\python\homework"
pre = 0
s3 = ".txt"
for i in range(1, 5):
pre = pre + 1
oldname = str(pre) + s3
print("name = " + str(pre) + s3)
s2 = input("Enter your input: ")
s1 = str(pre)
newname = s2 + s1 + s3
os.rename(path + "\\" + oldname, path + "\\" + newname)
print("success: " + newname)
print("----------------------------------------------------------")
2、读取一个文件,显示除了以#号开头的行以外的所有行
file = open("E:\作业\python\homework\shu5.txt",'r')
r = file.readlines()
for i in r:
if i[0] == '#':
continue
else:
print(i)
file.close()
3、已知文本文件中存放了若干个数字,请编写程序读取所有数字,排序以后进行输出
fl = open('E:\作业\python\homework\shu6.txt')
l = []
sort = []
for lines in fl.readlines():
lines = lines.replace("\n", "")
l.append(lines)
print('\n', 'the original file is:', l)
sort = sorted(l)
print('\n', 'the sorted file is:', sort)
4、打开一个英文的文本文件,将该文件中的每一个字母加密后写入到一个新文件,加密的方法是:将A变成B,B变成C,……,Y变成Z,Z变成A;a变成b,b变成c……,z变成a,其它字符不变化
file=open("E:\作业\python\homework\shu2.txt","r")
con=file.readline()
list=list(con)
file.close()
for i in range(0,len(list)):
if list[i].islower():
if list[i]=='z':
list[i]=chr(97)
continue
num=ord(list[i])
list[i]=chr(num+1)
if list[i].isupper():
if list[i]=='Z':
list[i]=chr(65)
continue
num=ord(list[i])
list[i]=chr(num+1)
new_Str=''.join(list)
print(new_Str)
file=open("3.txt","w+")
file.write(new_Str)
file.close()
5、打开一个英文文本文件,将其中大写字母变成小写,小写字母变为大写
txt = open(r"E:\作业\python\homework\shu7.txt")
r = txt.read()
print("修改前的字符:" + r)
txt1 = r.swapcase()
print("修改后的字符:" + txt1)