我的代码出了什么问题?蟒蛇

时间:2013-04-12 18:26:33

标签: python python-2.7

我在python编程但是我遇到了一些我无法解决的小问题!问题是,当它在文本文件中打印出来时,它只打印整个输出的一行!否则它有效!我需要帮助才能完成这项工作!

import sys, bz2, string, os
#instead of hardcoding filename, get it from arguments
#filename = os.getcwd()
filename = raw_input("Enter the path of bz2 document e.g. files/access_log-20130301.bz2: ")
print "Using file : " + filename
source_file = bz2.BZ2File(filename, "r") 
for line in source_file:
    #Extract the date and put into a variable 
    logdate = string.split(line)[3][1:12]
    #Extract movie name and put into variable movie
    movie = string.split(line)[6]
    #extract who read the movie username = 
    usernames = string.split(line)[2]
    #Only process the movie line if we have /media/movie in it. 
    if movie.find('media/movies') > 0:
        #Prints all things prosscesed
        print "User:" + usernames + " On:" +  logdate + " Was watching:"+ movie
        #p=open(filename+"record.txt", "w")
        fp=open(filename+"record.txt", "wb+")
        fp.write("User: " + usernames + " On: " +  logdate + " Was watching: "+ movie+" File from:"+filename+"\n")
sys.exit()

2 个答案:

答案 0 :(得分:1)

问题很可能是每次要编写一行时都打开文件的新文件句柄,而不是先刷新输出。这里有两种可能的解决方案:

  1. 在主for循环之前打开要写入的文件。这样,您将只有一个文件句柄,并且缺少刷新不会导致此行为。确保在完成后关闭文件。 (考虑使用with块,这将导致文件在块终止时自动关闭:with open(filename + "record.txt", "wb+") as f:
  2. fp调用后立即关闭fp.write(),这将强制刷新任何缓冲的输出,至少刷新到内核I / O缓存。
  3. 我更喜欢选项1,因为在这种情况下没有理由多次打开和关闭文件。 (如果你在文件中写了很多行,这些打开/刷新/关闭周期最终会浪费很多时间!)

    选项1看起来像这样:

    import sys, bz2, string, os
    #instead of hardcoding filename, get it from arguments
    #filename = os.getcwd()
    filename = raw_input("Enter the path of bz2 document e.g. files/access_log-20130301.bz2: ")
    print "Using file : " + filename
    with open(filename+"record.txt", "wb+") as fp:
        source_file = bz2.BZ2File(filename, "r") 
        for line in source_file:
            #Extract the date and put into a variable 
            logdate = string.split(line)[3][1:12]
            #Extract movie name and put into variable movie
            movie = string.split(line)[6]
            #extract who read the movie username = 
            usernames = string.split(line)[2]
            #Only process the movie line if we have /media/movie in it. 
            if movie.find('media/movies') > 0:
                #Prints all things prosscesed
                print "User:" + usernames + " On:" +  logdate + " Was watching:"+ movie
                #p=open(filename+"record.txt", "w")
                fp.write("User: " + usernames + " On: " +  logdate + " Was watching: "+ movie+" File from:"+filename+"\n")
    
    # The with block has ended at this point, so the file will already be closed here.
    
    sys.exit()
    

答案 1 :(得分:1)

您正在循环内以写入模式打开输出文件。在主回路之外打开一次。

完成后一定要关闭它。更好的是,写下:

with open(filename + "record.txt", "wb+") as fp:
    for line in source_file:
        ...
        fp.write(...)

以便open上下文管理器随后为您关闭它。