Python file operation exercises

1. Read a file and display all lines except the lines starting with #.

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()

Operation result:
Insert picture description here
Insert picture description here
2. It is known that there are some numbers stored in the text file. Please write a program to read all the numbers and output them after sorting.

f=open('number.txt','r')
total=f.read()
print(total)
number=[]
for i in total:
    number.append(i)
number.sort()
print(number)
f.close()

Problems encountered: how to recognize numbers other than 10, and how to delete if there are spaces and line breaks in the text.
Operation result:
Insert picture description hereInsert picture description here
3. Open an English text file, encrypt each letter in the file and write it to a new file. The encryption method is: change A into B, B into C,… Y becomes Z , Z becomes A; a becomes b, b becomes ... z becomes a, other characters do not change.

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()

Operation result:
Insert picture description here
Insert picture description here4. Open an English text file, and change the uppercase letters to lowercase and lowercase letters to uppercase.

f=open('English.txt','r')
content=f.read()
content=content.swapcase()#swapcase() 方法用于对字符串的大小写字母进行转换
print(content)
f=open('English.txt','w')
f.write(content)
f.close()

Operation result: Insert picture description here
Insert picture description here
5. In daily life, we often meet certain needs to modify the file name. With the help of the file operation we just learned, write a small program that can modify the file name in batches

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

Insert picture description hereInsert picture description here

Published 8 original articles · Like1 · Visits 382

Guess you like

Origin blog.csdn.net/weixin_42064000/article/details/105570275