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'编码='UTF-8'>
如果我用print(newfile)
替换print(newtext)
,它正好给了我想要的。我做错了什么?
要读取文件的内容,需要使用其.read()
方法:
newtext.seek(0) #Move the file pointer to the start of the file.
print(newtext.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):
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行: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'