读取文本文件并将其转换为大写,然后写入第二个文件。在
fo = open('/home/venkat/Desktop/Data Structure/Python/test.txt', 'r')
for x in fo.read():
y = x.upper()
fo1 = open('/home/venkat/Desktop/Data Structure/Python/write.txt', 'a')
fo1.write(y)
内容测试.txt:—我叫文卡泰什
正确输出:- 我叫文卡泰什
我得到了:- H我叫文凯特斯
H不是在最后一个位置出现,而是将第一个字符移到第二个字符。为什么?
问题是,你不再关闭你的文件了。只有在文件关闭时,sure才会写入数据。因为您为每个字符打开了一个新文件,并且没有显式地关闭这些文件,所以写入字符的顺序是不确定的。在
使用
with
语句打开文件可确保正确关闭文件:在行首添加换行符
\n
。在例如:
相关问题 更多 >
编程相关推荐