Python:读取文本文件并将其转换为大写,然后写入第二个fi

2024-10-06 08:52:08 发布

您现在位置:Python中文网/ 问答频道 /正文

读取文本文件并将其转换为大写,然后写入第二个文件。在

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不是在最后一个位置出现,而是将第一个字符移到第二个字符。为什么?


Tags: 文件testtxthomedataopen字符structure
2条回答

问题是,你不再关闭你的文件了。只有在文件关闭时,sure才会写入数据。因为您为每个字符打开了一个新文件,并且没有显式地关闭这些文件,所以写入字符的顺序是不确定的。在

使用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)

在行首添加换行符\n。在

例如:

with open(filename) as infile, open(filename1, "a") as outfile:
    for line in infile:
        outfile.write("\n" + line.upper())

相关问题 更多 >