[英]file.write() not permanently writing to file 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
但是,当我第二次运行脚本时,输出完全相同,并且当我检查文本文件时,最后的三个空格仍保留在那里。 如何永久删除此多余的间距?
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]
item = '12345'; item = item[:-3]
不会更改基础'12345'
字符串的值,它会创建一个新字符串并更改要引用它的item
引用的值。
一旦我弄清楚了它的工作原理,该语言的这一方面就大开眼界。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.