【发布时间】:2014-01-29 16:28:46
【问题描述】:
所以,我正在做一个项目,我必须对一个包含歌曲数据的 34mb 大文本文件进行排序。文本文件的每一行都有年份、唯一编号、艺术家和歌曲。我想不通的是如何有效地将数据排序到其他文本文件中。我想按艺术家姓名和歌曲名称排序。可悲的是,这就是我所拥有的:
#Opening the file to read here
with open('tracks_per_year.txt', 'r',encoding='utf8') as in_file:
#Creating 'lists' to put information from array into
years=[]
uics=[]
artists=[]
songs=[]
#Filling up the 'lists'
for line in in_file:
year,uic,artist,song=line.split("<SEP>")
years.append(year)
uics.append(uic)
artists.append(artist)
songs.append(song)
print(year)
print(uic)
print(artist)
print(song)
#Sorting:
with open('artistsort.txt', 'w',encoding='utf8') as artist:
for x in range(1,515576):
if artists[x]==artists[x-1]:
artist.write (years[x])
artist.write(" ")
artist.write(uics[x])
artist.write(" ")
artist.write(artists[x])
artist.write(" ")
artist.write(songs[x])
artist.write("\n")
with open('Onehitwonders.txt','w',encoding='utf8') as ohw:
for x in range(1,515576):
if artists[x]!= artists[x-1]:
ohw.write (years[x])
ohw.write(" ")
ohw.write(uics[x])
ohw.write(" ")
ohw.write(artists[x])
ohw.write(" ")
ohw.write(songs[x])
ohw.write("\n")
请记住,我是新手,所以请尽量用简单的语言进行解释。如果你们有任何其他想法,我也很想听听。谢谢!
【问题讨论】:
-
您不应该为此使用
range。如果文件中的条目数发生更改,它将破坏您的逻辑。您可以使用for line in artists:确保您始终检查每一行。 -
@IanAuld 感谢您的建议,但我一开始就这样做了。问题是,artistsort.txt 文件中没有写入任何内容,并且一击奇迹文件变得太大(~32mb)。
-
这与
for循环无关。在您之前的问题中,您的逻辑存在问题,阻止将任何内容写入文件。for循环只是迭代您的数据,它之后的内容决定了您的数据实际发生的情况。
标签: python sorting file-management