首页 > 解决方案 > 将整个文件大写

问题描述

我正在将文件附加到我的代码中,然后将文件转换为大写。Rn 它只是将文件大写的第一句变成了大写字母,其余的小写字母我尝试了 2 种不同的方式,我把两者都放了以防万一你想看到视觉效果(一个策略在标签中,而一个在代码中)。我怎样才能使整个文件变成大写?

newFile = open ('tobe.txt', 'r')
new_file = open ('tobeUPPER.txt','w')

#for line in newFile:
    #print (newFile.read()),
    #wholeFile = newFile.read()
#upperLine = wholeFile.upper()
#print (upperLine)


for line in newFile:
    print (newFile.read()),
newFile = open ('tobe.txt', 'r')
wholeFile = line.upper()
print (wholeFile)
new_file.write('tobeUPPER.txt', "w")

newFile.close()
new_file.close()

标签: pythonfile

解决方案


使用 打开这两个文件with,这将为您关闭文件。读取原始文件的内容,将它们转换为大写,然后将它们写入新文件。

with open('tobe.txt', 'r') as original_file:
    with open('tobeUPPER.txt', 'w') as new_file:
        new_file.write(original_file.read().upper())

推荐阅读