建立一个文件(c.txt),将以下内容存入到文件中。然后将该文件中的每个英文字母加密后写入到一个新文件(d.txt)。加密的方法是:将A变成B,B变成C,……,Y变成Z,Z变成A;a变成b,b变成c,……,y变成z,z变成a,其他字符不变化。
I say to you today, my friends.
And so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream.
with open("c.txt", "w") as file: # w只写方式。如果文件不存在,则新建;存在,则覆盖;a追加方式。如果文件不存在,则新建;存在,则打开继续操作
file.write("I say to you today, my friends.") # 写入数据
file.write("And so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream.")
with open("d.txt", "w") as fd:
with open("c.txt") as fc: # 默认“r”
line = fc.readline()
words = []
for letter in line: # 遍历字符
ascii = ord(letter) # 字符转ascii
tni = int(ascii) # 小写a97-z122,大写A65-Z90
if tni >= 97 and tni < 122:
tni += 1
elif tni == 122:
tni = 97
elif tni >= 65 and tni < 90:
tni += 1
elif tni == 90:
tni = 65
char = chr(tni) # ascii转字符
words.append(char)
encrypted = "".join(words)
fd.write(encrypted)