[英]How to write a list to a text file in python?
我正在艱難地學習python學習教程,並且我試圖制作一個包含一些基本概念的我自己的項目。 我們還沒有介紹循環,因此作為一個預警,如果您要在回答中包括一個循環,請在假設我以前從未見過的情況下進行循環:)
這是我的代碼,在我嘗試將列表寫入文件之前一直有效。 我收到寫期望字符串的錯誤消息。 有什么辦法欺騙寫成認為該列表是一個字符串嗎?
from sys import argv
script, file1 = argv
def rewind(f):
f.seek(0)
txt = open(file1, 'a+')
txt.write(raw_input("What would you like to add to the file?:\n"))
rewind(txt)
text = txt.read()
print text
def breakwords(f):
split_words = f.split(' ')
return split_words
brkwrds = breakwords(text)
print brkwrds
def sort_words(f):
sorted_words = sorted(f)
return sorted_words
sw = sort_words(brkwrds)
rewind(txt)
txt.truncate()
txt.write(sw)
您可以使用str.join
連接列表中的所有字符串:
my_list = ['a', 'few', 'words']
my_string = ' '.join(my_list)
在這里,我使用空格作為分隔符來連接my_list
所有字符串。 結果是可以寫入文件的字符串( 'a few words'
)。
您可以使用pickle將對象轉換為字符串,然后使用字符串對腌制后的字符串進行轉義,以使結果為一行(當存儲在文件中時)。
python 2X方法是:
from sys import argv
script, file1 = argv
import pickle
def rewind(f):
print(f.seek(0))
f.seek(0)
txt = open(file1, 'a+')
txt.write(raw_input("What would you like to add to the file?:\n"))
rewind(txt)
text = txt.read()
print text
def breakwords(f):
split_words = f.split(' ')
return split_words
brkwrds = breakwords(text)
print brkwrds
def sort_words(f):
sorted_words = sorted(f)
return sorted_words
sw = sort_words(brkwrds)
rewind(txt)
txt.truncate()
txt.write(pickle.dumps(sw).encode("string-escape")+"\n")
txt.close()
解碼文件中的腌制對象以重新獲得列表。 像這樣的東西
my_list_resurrected=pickle.loads(line_in_file.decode("string-escape"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.