【问题标题】:Can't read file after split line?分割线后无法读取文件?
【发布时间】:2016-03-12 12:55:48
【问题描述】:
file = open("songs.txt" , "r")
songs = {}

for line in file:
    (song, name) = line.split(",")
    songs[song] = str(name)

print(songs)

songs = {}

print("Welcome to the Virtual Playlist!")

while True:
    print("")
    print("What would you like to do?")
    print("1. View the playlist")
    print("2. View playlist sorted by artist name")
    print("3. View playlist sorted by song name")
    print("5. Add a song")
    print("6. Exit")
    choice = input("").strip()

    if choice == "1":
        print(file.read())

我正在尝试从文件中读取然后输出其中的所有内容,如果我排除它读取每一行并将其存储到字典中的部分,它工作正常。但是,如果包含该部分,它将不起作用。为什么会这样?

此外,当它将歌曲和艺术家存储到字典中时,它会在某些条目中包含 /n,因为文件中有空格。有什么方法可以排除 /n 的东西,因为我只是不想歌曲名称/艺术家。

【问题讨论】:

    标签: file python-3.x if-statement for-loop


    【解决方案1】:

    在此循环for line in file: 之后,您位于文件末尾。因此,下一个file.read() 没什么可看的。如果你真的想再次读取文件,你可以转到开头:

    file.seek(0)
    

    可是songs里的歌你都已经看完了,为什么要重新定义songs = {}再删掉呢?为什么不:

    if choice == "1":   
        for song, name in songs.items():
            print(name, song)
    

    使用strip() 去掉\n 字符:

    song, name = line.strip().split(",")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多