关于python:如何读取我刚写入的文件

How to read a file i have just written to

1
2
3
4
5
6
7
8
9
10
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(newfile)替换print(newtext),它会给我想要的。我做错什么了?


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

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


你要做的是:

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

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

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

在第10行,打印文件描述符(newtext时,python显示该文件描述符的表示:

类名:textiographer

文件名:mydata.out

开启方式:W

编码:utf-8

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

如果要在写入后读取文件,则需要以读/写模式打开文件:"w+":

1
2
3
4
5
6
>>> 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'


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

1
2
3
4
5
6
7
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())

或者只打印每一行:

1
2
3
4
5
6
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())