将文件中的所有字符转换为小写

2024-06-09 09:59:57 发布

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

#文件名:abc.txt
#文件内容:你选错房子了,傻瓜

我想把我的文件读成小写的。我试着使用下面的代码,但我得到了一个错误'_io.TextIOWrapper' object has no attribute 'lower'

reader = open('abc.txt', 'r')
low = reader.lower()
for line in low:
    print(line)        
reader.close() 

预期结果:你选错房子了,傻瓜


Tags: 文件代码iotxt内容文件名错误line
3条回答

您可以使用with open(filename, 'r') as f,这样就不必关闭文件。其次,您不能以这种方式使用文件-您应该使用for循环对它们进行迭代:for line in f。行本身是一个字符串,这意味着您可以使用line实现lower()函数

with open('abc.text', 'r') as f:
    for line in f:
        line = line.strip()  # getting rid of the '\n'
        line = line.lower()
        print(line)

reader不存储文件内容,您需要首先read()

text = open('abc.txt', 'r').read()
low = text.lower()

也可以优选使用with

with open('abc.txt', 'r') as file:
    for line in file.read():
        print(line.lower())

解决办法如下:

oldFileContent = open("file.txt", "r").read()
newFileContent = oldFileContent.lower()

with open("file.txt", "w") as f:
    f.write(newFileContent)

因此,您忘记了“读取()”文件,然后对读取的文件内容调用“lower()”

祝你好运

相关问题 更多 >