【问题标题】:Why won't python append to this file?为什么python不会附加到这个文件?
【发布时间】:2014-01-10 14:08:56
【问题描述】:

所以,我正在做这个项目,我有一个 34mb 的文本文件,里面有歌曲数据。每一行都有年份、艺术家、唯一编号和歌曲,由字符串<SEP> 分隔。现在,我已将这些东西中的每一个分类到不同的列表中。我现在要做的是将艺术家分类到不同的文本文件中。问题是 python 将创建文件但不会打印到它,文件大小为 0 字节。这是我的代码:

#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('artistssorted.txt', 'a') as artist:

    for x in range(1000000):
        x=1
        if artists[x-1]==artists[x]:
            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")
        else:
            x=x+1

仅供参考,uics= 唯一标识符代码 另外,如果你们对如何排序这个文件有任何其他建议,我很高兴听到它。请记住,我是新手。

【问题讨论】:

  • 您的for 循环看起来有点奇怪。为什么x=1x = x+1? x 应该在没有这些的情况下自动增加。如果您希望循环从 1 开始,请执行 for x in range(1, 10000000):
  • 你知道第二个for循环是无限的吗?
  • @EarlGrey 它不是无限的,但它总是会写入第一个值。 range 最终将引发 StopIteration
  • 您应该将信息存储在元组列表中(艺术家、年份、uic、歌曲),然后对其进行排序。
  • @WayneWerner 如果前两个条目不相等,则不会写入。

标签: python file file-io


【解决方案1】:

如果前 2 个艺术家条目不相等,则您的条件 if artists[x-1]==artists[x]: 将始终为 false,因为您在每次循环迭代时将 x 覆盖为 1。写入文件将永远不会发生。

使用范围迭代时,变量会自动递增,因此无需自己进行。

【讨论】:

    【解决方案2】:

    这是我的命中:

    #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
        records = []
    
        #Filling up the 'lists'
        for line in in_file:
            year, uic, artist, song=line.split("<SEP>")
            records.append((artist, year, uic, song))
    
    #Sorting:
    records.sort()
    with open('artistssorted.txt', 'a') as artist_file:
    
        for (artist, year,uic,song) in records:
            artist_file.write("%s %s %s %s\n"%(year, uic, artist, song))
    

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 2016-05-11
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      相关资源
      最近更新 更多