读取文本文件并将其转换为大写并写入第二个文件。
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)
test.txt 的内容:-我的名字是 Venkatesh
正确的输出:- 我的名字是 VENKATESH
我得到 :- H我的名字是 VENKATES
H 不是在最后一个位置,而是将第一个字符移到第二个字符。为什么?
问题是,您不再关闭文件了。数据仅在文件关闭时确定写入。由于您为每个字符打开了一个新文件,并且没有明确关闭这些文件,因此写入的字符顺序是不确定的。
使用该with
语句打开文件可确保正确关闭文件:
with open('/home/venkat/Desktop/Data Structure/Python/test.txt', 'r') as inp:
y = inp.read().upper()
with open('/home/venkat/Desktop/Data Structure/Python/write.txt', 'a') as out:
out.write(y)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句