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) |
我正在尝试获取一个文件(
<_io.TextIOWrapper name='mydata.out' mode='w' encoding='UTF-8'>
如果我用
要读取文件的内容,需要使用其
1 2 | newtext.seek(0) #Move the file pointer to the start of the file. print(newtext.read()) |
你要做的是:
第3行:
第5-8行:
第10行:打印文件描述符(
在第10行,打印文件描述符(
类名:textiographer
文件名:mydata.out
开启方式:W
编码:utf-8
当您打印
如果要在写入后读取文件,则需要以读/写模式打开文件:"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()) |