有一个英文文件“example.txt”,请编写一个程序把大写字母变为小写,小写字母变为大写,其他字符不变.结果写入文件“result.txt”。

有一个英文文件“example.txt”,请编写一个程序把大写字母变为小写,小写字母变为大写,其他字符不变.结果写入文件“result.txt”。

with open('example.txt', 'r') as f:
    content = f.read()
result = ""
for char in content:
    if char.isupper():
        result += char.lower()
    elif char.islower():
        result += char.upper()
    else:
        result += char
with open('result.txt', 'w') as f:
    f.write(result)

1、先打开example.txt文件,with语句块(自动关闭打开的文件);读取所有内容read();
2、大写转小写,小写转大写,用swapcase();
3、再将转换后的内容写入result.txt。先打开,'w'可覆盖文件内容,'a'可追加内容;再写入wirte()。

with open('example.txt') as f1:
    content = f1.read()
with open('result.txt','w') as f2:
    f2.write(content.swapcase())