从列表到文件写入更改的值,第二次迭代不起作用,Python

时间:2017-01-27 21:17:30

标签: python file

以下功能是较大程序的一部分,旨在让用户“喜欢”一部电影并在电影文本文件中存储该值(通过递增)。奇怪的是,它在第​​一次迭代中工作正常(将其读入列表,更改值,将其写入文件),但在第二次迭代时,会发生错误。

该文件名为“films.txt,内容为:

    0,Genre,Title,Rating,Likes
    1,Sci-Fi,Out of the Silent Planet,PG,0
    2,Sci-Fi,Solaris,PG,0
    3,Sci-Fi,Star Trek,PG,0
    4,Sci-Fi,Cosmos,PG,0
    5,Drama,The English Patient,15,1
    6,Drama,Benhur,PG,0
    7,Drama,The Pursuit of Happiness,12,0
    8,Drama,The Thin Red Line,18,0
    9,Romance,When Harry met Sally,12,0
    10,Romance,You've got mail,12,0
    11,Romance,Last Tango in Paris,18,0
    12,Romance,Casablanca,12,0

此特定功能的代码如下:注意:idnumber是指每部电影的idnumber。例如,StarTrek的id号是3。

def likeafilm(x,username):
#prompt the user to enter the ID number they require
   idnumber=int(input("To confirm, please enter the number of the film you wish to like:"))
   #create a list which stores and displays all the data in the films txt file
   with open("films.txt",mode="r", encoding="utf8") as f:
      allfilms=[]
      reader=csv.reader(f)
      for row in reader:
         allfilms.append([element.strip() for element in row])

         #print(allfilms)
      print("print the third film", allfilms[3])
      print("print the second film", allfilms[2])
      print("print the current film selected", allfilms[idnumber])
      print("print the like for current film", allfilms[idnumber][4])

      allfilms[idnumber][4]=str(int(allfilms[3][4])+1) #this succesfully increments the record in the runtime list by 1
      print(allfilms) #this confirms the update - this now needs to be written to file.

   with open("films.txt","w") as f:
      writer=csv.writer(f)
      writer.writerows(allfilms)

   print("******BACK TO VIEWING FILMS SELECTION***********")
   watchfilms(username)

在第一次迭代,或第一次运行程序时,它工作正常! 1增加(对于喜欢的人),一切都很好。发生的错误如下,第二次......

    print("print the like for current film", allfilms[idnumber][4])
    IndexError: list index out of range

更新代码

def likeafilm(x,username):
#prompt the user to enter the ID number they require
   idnumber=int(input("To confirm, please enter the number of the film you wish to like:"))
   #create a list which stores and displays all the data in the films txt file
   with open("films.txt",mode="r", encoding="utf8") as f:
      allfilms=[]
      reader=csv.reader(f)
      for row in reader:
         allfilms.append([element.strip() for element in row])

         #print(allfilms)
      print("print the third film", allfilms[3])
      print("print the second film", allfilms[2])
      print("print the current film selected", allfilms[idnumber])
      print("print the like for current film", allfilms[idnumber][4])

      allfilms[idnumber][4]=str(int(allfilms[3][4])+1) #this succesfully increments the record in the runtime list by 1
      print(allfilms) #this confirms the update - this now needs to be written to file.

   with open("films.txt","w") as f:
      writer=csv.writer(f)
      #writer.writerows(allfilms)
      allfilms.append([element.strip() for element in row])
      writer.writerows(allfilms)

   print("******BACK TO VIEWING FILMS SELECTION***********")
   watchfilms(username)    

正如Apollo在下面提到的那样,我可以看到发生了什么(错误),但不知道如何修复它。它适用于第一次迭代,因为文件是正确的(没有空格)。然而,在SECOND迭代中,文件已被覆盖,并且它似乎对文件的内容做了一些事情。第二次出现这个错误:

    print("print the like for current film", allfilms[idnumber][4])
  IndexError: list index out of range

我尝试了这部电影5(英国病人 - 顺便说一句很棒的电影),虽然它第一次更新了它,并且喜欢增加到“1”,第二次,它没有。

我也尝试将文件编写器更改为“wb”而不是“w”,但也出现了以下错误:

writer.writerows(records)
TypeError: 'str' does not support the buffer interface

2 个答案:

答案 0 :(得分:0)

你有正确的想法,但我会把它分成两个功能,一个用于增加电影,一个用于用户互动。另外,您在调用内置函数open()时尝试指定' encoding',这不是有效参数。

import csv

films_file = "films.txt"

def like_film(x):
    with open(films_file,mode="r") as f:
        reader = csv.reader(f)
        records = [row for row in reader]
    for rec in records:
        if int(rec[0]) == x:
            rec[-1] = str(int(rec[-1]) + 1)
    with open("films.txt","wb") as f:
        writer=csv.writer(f)
        writer.writerows(records)

def user_like_film(username):
    x = int(input("Enter the ID of the film you wish to like: "))
    like_film(x)
    watchfilms(username)

答案 1 :(得分:0)

找到答案:

在Python 2中,需要使用'wb'打开文件,如您所建议的那样,而不是'w'。

然而,我使用Python 3.在Python 3中,所需的语法略有不同。需要使用附加参数打开文件,即:newline =''而不是。

以下示例:

# Python 2
with open('filmsfile.txt', 'wb') as f:
    writer = csv.writer(f)

# Python 3
with open('filmsfile.txt', 'w', newline='') as f:
    writer = csv.writer(f)