简体   繁体   English

没有在 python 的新文件中写入 output 的所有行

[英]not writing all lines of output in a new file in python

I am creating a file and I want to write all lines of write_line to my output.我正在创建一个文件,我想将 write_line 的所有行写入我的 output。 With this could I have a new file but only with the last line of write_log not all the lines.有了这个,我可以有一个新文件,但只有 write_log 的最后一行,而不是所有行。 I think I should have a for before written log and tell to write all, but i am so new with python and need help.我想我应该有一个之前写的日志并告诉写所有,但我对 python 很陌生,需要帮助。 I am getting name / familtname / id by SOAP response.我收到 SOAP 响应的姓名/家庭名称/身份证。 I want to print responses which are in lines, now i just see the last line not all the lines.我想打印成行的响应,现在我只看到最后一行而不是所有行。

timestamp = str(datetime.datetime.now())[:19]
file = open(CreateFile, 'w') 
write_line = str(name).strip() + ';' + familyname.strip() + ';' + str(id).strip() + ';' + timestamp
file.writelines(write_line + '\n') 


def CreateFile():#******************creating output log file*****
    today = str(datetime.date.today()).split('-')
    NowTime = str(datetime.datetime.now())[11:19:]
    Nowtime_split = NowTime.split(':')
    timestamp=Nowtime_split[0]+Nowtime_split[1]+Nowtime_split[2]
    daystamp=today[0]+today[1]+today[2]
    filename = 'log' + '_' + daystamp + '_' + timestamp + '.csv'
    destfile = r'C:\Desktop' + str(filename)
    file = open(destfile, 'w') 
    file.close() 
    return(destfile)
CreateFile=CreateFile()

this is a small case:这是一个小案例:

import datetime
timestamp = str(datetime.datetime.now())[:19]
file = open('1.txt', 'w') 
for i in range(10):
    write_line ='try'+str(i)
    file.writelines(write_line + '\n') 
file.close()

` `

I'm not really sure what you want but I think the problem is because you're using write parameter to open the file and it's always replacing the previous text, so what you can do is replacing write with append(a) :我不太确定你想要什么,但我认为问题是因为你使用write参数打开文件并且它总是替换以前的文本,所以你可以做的是用append(a)替换write

timestamp = str(datetime.datetime.now())[:19]

with open(CreateFile, 'a') as file:
    write_line = str(name).strip() + ';' + familyname.strip() + ';' +str(id).strip() + ';' + timestamp
    file.write(write_line + '\n') 

I suggest you to use with open... in order to avoid closing the file opened and other futures errors我建议您使用with open...以避免关闭打开的文件和其他期货错误

lines = ['line1', 'line2', ...] # set of lines (list) you want to add in the current timestamp file with open('current_timestampfile.txt', 'w') as f: f.writelines("%s\n" % l for l in lines)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM