gpt4 book ai didi

python - 在 Unix/Linux 上不会将输出写入日志文件,但在 Windows 上会写入

转载 作者:行者123 更新时间:2023-11-30 23:45:31 24 4
gpt4 key购买 nike

我有以下代码,它将在两个平台上创建日志文件,但它只会将输出写入 Windows 日志文件。

import os                       

logdir = os.getenv("logs")
logfile = 'script_list.log'
path = (raw_input("Enter dir: "))
if os.name == "posix":
log = open("//".join([logdir,logfile]), 'w')
else:
log = open("\\".join([logdir,logfile]), 'w')
for dirpath, dirname, filenames in os.walk(path):
for filename in [f for f in filenames]:
if os.name == "posix":
log.write(str(dirpath)+ "//" + str(filename) + "\n")
else:
log.write(str(dirpath)+ "\\" + str(filename) + "\n")
print '\nYour logfile ' + logdir + '\\' + logfile + ' has been created'

提前致谢

最佳答案

建议你更换

if os.name == "posix":
log = open("//".join([logdir,logfile]), 'w')
else :
log = open("\\".join([logdir,logfile]), 'w')
...
for filename in [f for f in filenames]:
if os.name == "posix":
log.write(str(dirpath)+ "//" + str(filename) + "\n")
else:
log.write(str(dirpath)+ "\\" + str(filename) + "\n")

log=open(os.path.join(logdir, logfile), 'w')
...
for filename in filenames:
log.write(os.path.join(dirpath, filename)+'\n')

或者更好的是,使用

logfilename=os.path.join(logdir, logfile)
log=open(logfilename, 'w')

...

print "Your logfile", logfilename, "has been created."

@Lycha says ,最好再次关闭文件。所以你的构造将是

with open(logfilename, 'w') as log:
...

关于python - 在 Unix/Linux 上不会将输出写入日志文件,但在 Windows 上会写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9483920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com