我正在將檔案讀入串列。現在我想要,我串列中的每一個昏迷后,都應該有一個新的索引。到目前為止,所有內容都放在索引 0 中。
相關代碼:
def add_playlist():
playlist_file_new =filedialog.askopenfilename(initialdir=f'C:/Users/{Playlist.username}/Music',filetypes=[('Playlistdateien','.txt')])
with open (playlist_file_new,'r') as filenew:
filenew_content = list(filenew.readlines())
print(filenew_content[0])
那么,我該怎么做才能在每個逗號之后開始一個新索引?請幫助我,我提前謝謝你。如果這是一個非常基本的問題,我也很抱歉,我對編程真的很陌生。
uj5u.com熱心網友回復:
我沒有嘗試您的代碼,但我會這樣做:
with open (playlist_file_new,'r') as filenew:
filenew_content = filenew.read()
filenew_content_list = filenew_content.split(",")
這會將檔案的完整資料(請注意大于作業記憶體 (RAM) 的檔案)讀入變數 filenew_content。它以字串形式回傳。Python 中的字串物件具有“split()”方法,您可以在其中定義一個字串,在其中拆分較大的字串。
uj5u.com熱心網友回復:
可能你想要的是.split()功能:https ://docs.python.org/3/library/stdtypes.html#str.split
uj5u.com熱心網友回復:
而不是使用list(),使用str.split()。為此,您不能使用 readlines(),因為它會回傳行串列。
你正在尋找這樣的東西:
filenew_content = playlist_file_new.read().split(",")
這將獲取檔案物件,獲取包含其內容的字串,并將其拆分為串列,使用逗號作為分隔符。
uj5u.com熱心網友回復:
如果你的意思是你想list[str]變成list[str, str, str…],你可以使用該str.split(str)方法。請參閱以下內容:
l = ["hello,world,this,is,a,list"]
new_l = l[0].split(",")
print(new_l)
>>> ["hello", "world", "this", "is", "a". "list"]
uj5u.com熱心網友回復:
string.split(',') 方法應該可以作業。例如
# loop over all the lines in the file
for line in filenew.readlines():
items = line.strip().split(',')
# strip strips the line of leading and trailing whitespace.
# split returns a tuple of all the strings created by
# splitting at the given character.
# loop over all the items in the line
for item in items:
# add them to the list
filenew_content.append(item)
另請參閱:字串的 Python 檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456143.html
