[英]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.