如何在python中操作txt文件使其全部小写



假设我有一个txt文件,我必须将其全部小写。我试过这个

def lowercase_txt(file):
file = file.casefold()
with open(file, encoding = "utf8") as f:
f.read()

我得到了"str对象没有属性"read">

然后我试了

def lowercase_txt(file):
with open(poem_filename, encoding="utf8") as f:
f = f.casefold()
f.read()

此处的"_io.TextIOWrapper"对象没有属性"casefold">

我能做什么?

编辑:我重新运行了这个确切的代码,现在没有错误(不知道为什么(,但文件根本没有改变,所有的字母都保持原样。

这将重写文件。警告:如果在处理过程中出现某种类型的错误(电源故障、咖啡洒在电脑上等(,您可能会丢失文件。因此,您可能需要首先备份您的文件:

def lowercase_txt(file_name):
"""
file_name is the full path to the file to be opened
"""
with open(file_name, 'r', encoding = "utf8") as f:
contents = f.read() # read contents of file
contents = contents.lower() # convert to lower case
with open(file_name, 'w', encoding = "utf8") as f: # open for output
f.write(contents)

例如:

lowercase_txt('/mydirectory/test_file.txt')

更新

以下版本打开文件进行读取和写入。读取文件后,在重写内容之前,文件位置将重置为文件的开头。这可能是一个更安全的选择。

def lowercase_txt(file_name):
"""
file_name is the full path to the file to be opened
"""
with open(file_name, 'r+', encoding = "utf8") as f:
contents = f.read() # read contents of file
contents = contents.lower() # convert to lower case
f.seek(0, 0) # position back to start of file
f.write(contents)
f.truncate() # in case new encoded content is shorter than older

相关内容

最新更新