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'模式=' W'编码=' UTF-8'>
如果我用print(newtext)
替换print(newfile)
,它会给我我想要的内容。我做错了什么?
答案 0 :(得分:4)
要阅读文件的内容,您需要使用其.read()
方法:
newtext.seek(0) #Move the file pointer to the start of the file.
print(newtext.read())
答案 1 :(得分:0)
您可以在读写模式下打开输出文件,
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())
答案 2 :(得分:0)
你在做的是:
第3行:r_t = 1 # thermal resistance
t_cold = 0.8 # cooling temp
t_hot = 2.2 # heating temp
t_lo, t_hi = 1, 2 # controller thresholds
c_t = 100 # heat capacity
t_obj = [0] # really cold start temp
h = []
for s in range(1000):
if t_obj[-1] < t_lo: # bang-bang logic
heat = 1
elif t_obj[-1] > t_hi:
heat = 0
# equation integrating the the heat/cooling input to t_obj
t_obj += [t_obj[-1] + ((heat * t_hot + (1 - heat) * t_cold) - t_obj[-1])/r_t/c_t]
h.append(heat)
plt.plot(h) # debug plot of `heat` state
plt.plot(t_obj)
包含输出文件的文件描述符。
第5-8行:newtext
包含您要输出的文字。
第10行:您打印文件描述符(newfile
)和输出文本(newtext
)。
在第10行,当您打印文件描述符(newfile
)时,python会显示此文件描述符的表示:
班级名称:TextIOWrapper
你的文件名:mydata.out
开场模式:w
和编码:UTF-8
当您打印newtext
时,它会显示您之前创建的字符串。
如果您想在写入文件后阅读文件,需要以读/写模式打开:“w +”:
newfile