Python重写文件而不是附加

2024-10-01 07:13:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个个人电视节目和电影数据库,我使用Python来获取电视节目和电影的信息。我有一个文件来获取文件夹中的电影信息,这很好用。在

我还有一个Python文件,它可以获取电视节目的信息(它是一个文件夹,例如Game of Thrones),它还可以从文件夹中获取所有的插曲文件,并获取这些文件的信息(格式如下:例如Game of Thrones;3;9

所有这些信息都存储在MySQL可以读取的两个文本文件中:tvshows.txt和{}。在

Python很容易在节目的第一部分获取电视节目的信息。在

程序的第二部分是在电视节目文件夹中获取每一集,并将信息存储在一个文件中(episodes.txt):

def seTv(show):
  pat = '/home/ryan/python/tv/'
  pat = pat + show
  epList = os.listdir(pat)
  fileP = "/home/ryan/python/tvtext/episodes.txt"
  f = open(fileP, "w")
  print epList
  hdrs = ['Title', 'Plot', 'imdbRating', 'Season', 'Episode', 'seriesID']
  def searchTvSe(ep):
    ep = str(ep)
    print ep
    seq = ep.split(";")
    print seq
    tit = seq[0]
    seq[0] = seq[0].replace(" ", "+")
    url = "http://www.omdbapi.com/?t=%s&Season=%s&Episode=%s&plot=full&r=json" % (seq[0], seq[1], seq[2])
    respo = u.urlopen(url)
    respo = json.loads(str(respo.read()))
    if not os.path.exists("/var/www/html/images/"+tit):
      os.makedirs("/var/www/html/images/"+tit)
    imgNa = "/var/www/html/images/" + tit + "/" + respo["Title"] + ".jpg";
    for each in hdrs:
      #print respo[each] # ==== This checks to see if it is working, it is =====
      f.write(respo[each] + "\t")
      urllib.urlretrieve(respo["Poster"], imgNa)

  for co, tt in enumerate(epList):
    f.write("\N \t" + str(co) + "\t")
    searchTvSe(tt)
    f.write("\n")
  f.close()

fullTv()

第二部分只工作一次,我有3个文件夹在tv文件夹(Game of ThronesBreaking BadThe Walking Dead)里面,这些文件里是这个系列的一集(Game of Thrones;3;4Breaking Bad;1;1The Walking Dead;3;4)。在

在我添加“seriesID”并更改文件之前(在每个文件夹都有一个文本文件之前,这是需要的,因为我为每个电视节目都有一个表)。在

episodes.txt中,权力游戏的信息是唯一出现的。我删除了“权力的游戏”文件夹,似乎最后要搜索的是唯一添加的文件夹。它似乎要覆盖它?在

谢谢。在


Tags: 文件oftxt文件夹信息gamewwwseq
2条回答

更改此行:

f = open(fileP, "w")

为此:

f = open(fileP, "a")

您需要用'a'而不是'w'打开文件:

with open('file.txt', 'a') as myfile:
     myfile.write("Hello world!")

您可以在https://docs.python.org/2/library/functions.html#open上的文档中找到更多详细信息。在

相关问题 更多 >