【问题标题】:How to read a file i have just written to如何读取我刚刚写入的文件
【发布时间】:2014-06-10 11:42:02
【问题描述】:
def createOutfile(text,lines,outfile):
    infile = open(text, 'r')
    newtext = open(outfile, 'w')
    count = 0
    newfile = ''
    for line in infile:
        count = count + 1
        newfile = newfile + "{0}: {1}".format(count,line)
    newtext.write(newfile)
    print(newtext)

我正在尝试获取一个文件 (text) 并创建该文件 (outfile) 的副本,该副本仅对行进行编号。我现在的代码没有打印错误,但它给了我这个:

<_io.textiowrapper name="mydata.out" mode="w" encoding="UTF-8">

如果我将print(newtext) 替换为print(newfile),它就会给我我想要的。我做错了什么?

【问题讨论】:

    标签: python file


    【解决方案1】:

    要读取文件的内容,您需要使用其.read() 方法:

    newtext.seek(0)       #Move the file pointer to the start of the file.
    print(newtext.read())
    

    【讨论】:

    • 然后它给了我这个错误:io.UnsupportedOperation: not readable 知道为什么会这样吗?
    • @user3330472 啊!没看到你用'w'(只写)模式打开文件,用'r+'读/写模式打开文件。
    【解决方案2】:

    您可以以读写模式打开输出文件,

    def number_lines(old_file_name, new_file_name, fmt="{}: {}"):
        with open(old_file_name) as inf, open(new_file_name, "w+") as outf:
            for i,line in enumerate(inf, 1):
                outf.write(fmt.format(i, line))
            # show contents of output file
            outf.seek(0)    # return to start of file
            print(outf.read())
    

    或者直接打印每一行:

    def number_lines(old_file_name, new_file_name, fmt="{}: {}"):
        with open(old_file_name) as inf, open(new_file_name, "w+") as outf:
            for i,line in enumerate(inf, 1):
                numbered = fmt.format(i, line)
                outf.write(numbered)
                print(numbered.rstrip())
    

    【讨论】:

      【解决方案3】:

      你正在做的是:

      第 3 行:newtext 包含输出文件的文件描述符

      第 5-8 行:newfile 包含您要输出的文本

      第 10 行:打印文件描述符 (newtext) 和输出文本 (newfile)。

      在第 10 行,当您打印文件描述符 (newtext) 时,python 会显示此文件描述符的 表示形式

      类名:TextIOWrapper

      你的文件名:mydata.out

      开启方式:w

      和编码:UTF-8

      当您打印newfile 时,它会显示您之前创建的字符串。

      如果你想在写入文件后读取它,你需要以读/写模式打开它:“w+”:

      >>> f = open("File", "w+")  # open in read/write mode
      >>> f.write("test")         # write some stuff 
      >>> # the virtual cursor is after the fourth character.
      >>> f.seek(0)               # move the virtual cursor in the begining of the file
      >>> f.read(4)               # read the data you previously wrote.
      'test'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-28
        • 2020-02-19
        • 2013-12-16
        • 1970-01-01
        • 1970-01-01
        • 2011-01-18
        • 1970-01-01
        相关资源
        最近更新 更多