文件.write()未永久写入python文件

2024-06-14 08:19:27 发布

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

我有一个名字的文本文件,所有的名字后面都有三个空格,我想删除。当我用python打印这些名称时,得到如下输出:

Adeline Panella Â
Winifred Aceto  
See Weckerly Â
Daniell Hildebrand Â
Betsey Coulter  
#there are about 1000 of these names

为了删除多余的空格,我编写了以下脚本:

import os
script_directory = os.path.dirname(__file__)
file = open(os.path.join(script_directory, "assets/data/names.txt"), 'r')
potential_names = file.read().splitlines()
potential_names = list(filter(None, potential_names))
for item in potential_names:
    print(item)
    item = item[:-3]
    print(item)
file.close()
file = open(os.path.join(script_directory, "assets/data/names.txt"), 'w')
for item in potential_names:
    file.write("{}\n".format(item))
file.close()

它似乎按预期工作,输出如下:

Adeline Panella  
Adeline Panella
Winifred Aceto  
Winifred Aceto
See Weckerly  
See Weckerly
Daniell Hildebrand  
Daniell Hildebrand
Betsey Coulter  
Betsey Coulter

但是:当我第二次运行脚本时,输出是完全相同的,当我检查文本文件时,最后的三个空格仍然存在。如何永久删除此额外间距?你知道吗


Tags: namesositemfilepotential空格seedaniell
1条回答
网友
1楼 · 发布于 2024-06-14 08:19:27
for item in potential_names:
    print(item)
    item = item[:-3]
    print(item)

当您更改上面第三行的item时,它不会反映回potential_names集合,它只是更改item。这就是为什么它似乎在修改字符串(1)。你知道吗

但是,稍后处理集合时:

for item in potential_names:

这就是要输出的集合的原始内容。你知道吗

解决这个问题的一种方法是简单地构建一个新的列表,从每个项目中删除最后三个字符:

potential_names = [x[:-3] for x in potential_names]

(1)Python通常被认为是一种纯面向对象的语言,因为一切都是名称所指的对象。你知道吗

它有一定的局限性,因为表达式item = '12345'; item = item[:-3]不会更改底层'12345'字符串的值,它会创建一个新的字符串并更改item引用的值来引用它。你知道吗

这方面的语言是一个真正的大开眼界,一旦我明白了它的工作原理。你知道吗

相关问题 更多 >