【问题标题】:Correct way to read and write file in python [duplicate]在python中读写文件的正确方法[重复]
【发布时间】:2020-06-28 16:47:00
【问题描述】:

我正在编写此函数以从文件中读取并写入另一个输出文件,但我没有收到任何输出。我是否正确编写了这些函数?如果它们是正确的,则问题出在解码函数的主体中,我将尝试解决。

代码:

def ReadFile():                                                                 #Reads data from file
    try:
        count=0
        stringvar=INFILE.open("K:\Data.txt","r")
        for line in INFILE:
            mylist.append(line.rstrip())
            count+=1
        INFILE.close()
        return count
    except:
        print("File could not be found")
        exit()


编写输出文件代码:

def WriteFile(outlist):                             #outputs data to output list
    OUTFILE=open("Output.txt","a")
    for details in outlist:
        OUTFILE.write(details+"/n")
        parselist.append(a+": Was issued by " +b+ " in "+c+".""The card expires on "+d1+"/"+d2+".The card i linked to" +e+ "with account number:" +f)
    OUTFILE.close()

上面的代码有问题吗?

如果有帮助,我会发布我编写的整个代码。

【问题讨论】:

  • 这能回答你的问题吗? How to read a file line-by-line into a list?
  • 你有没有试过在文件读取之后打印mylist的内容,在文件写入之前打印outlist的内容?查看文件是否被实际读取以及解码是否正确完成可能会有所帮助。
  • 不确定你为什么有INFILE.open?它应该只是open(your_file, "r")
  • 我会尽快尝试
  • btw:最好使用 with 语句,例如:with open(<file>, <mode>, ...) as opened_file: <do your stuff here>。因此,您可以在块内定义需要完成的操作,而无需在最后关闭文件。一切都由幕后使用的上下文管理器为您完成。

标签: python function output


【解决方案1】:

您通常使用with 关键字写入文件。我们这样做是为了调用上下文管理器。通过使用 dundermethods 或魔术方法,我们可以指定当文件没有正确写入或读取时会发生什么,这样如果代码在能够这样做之前失败,我们总是能够关闭所述文件。看这个例子:

class File:
def __init__(self, file_name, method):
    self.file = open(file_name, method)

def __enter__(self):
    print("Enter")
    return self.file

def __exit__(self, type, value, traceback):
    print("Exit")
    self.file.close()

with File("file.txt", "w") as f:
print("Middle")
f.write("hello!")   #Even if there is an exception and/or we didn't specify a file.close, 
                    #it does so because of the dundermethod we defined in the class.

【讨论】:

  • 请将您的代码作为(格式正确的)文本包含在您的答案中。从代码图像中复制和粘贴是不可能的,因此可能没有人会运行您的示例。
  • @Blckknght 这更好吗?
  • 改进了!缩进有点乱,修好了就好了。
【解决方案2】:

这很容易解决,只需尝试这样做:

def WriteFile(outlist):                             #outputs data to output list
    with open("Output.txt","a") as OUTFILE:
        for details in outlist:
            OUTFILE.write(details+"/n")
            parselist.append(a+": Was issued by " +b+ " in "+c+".""The card expires on "+d1+"/"+d2+".The card i linked to" +e+ "with account number:" +f)

只需使用with open(...) as ...,它就会起作用,如果它抛出错误,你可以尝试这样做:OUTFILE.write(str(details)+"/n"),它会起作用。希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2016-08-11
    • 2021-10-10
    相关资源
    最近更新 更多