Pythonファイル操作の演習

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

ここに画像の説明を挿入ここに画像の説明を挿入

オリジナルの記事を8件公開 いいね1 訪問数382

おすすめ

転載: blog.csdn.net/weixin_42064000/article/details/105570275