繁体   English   中英

Python os.makedirs在主目录中不起作用

[英]Python os.makedirs not working in home directory

我有这个Python脚本,它创建一个主文件夹,然后在每次运行时写入一个新文件#.log。

import os

os.makedirs(os.path.expanduser('~/logs'), exist_ok=True)
os.chdir(os.path.expanduser('~/logs'))
filenumber = 0
while (os.path.isfile("{0}.log".format(filenumber))):
    filenumber = filenumber + 1
log = open('{0}.log'.format(filenumber), mode='a', encoding='utf-8')
log.close
print("Log succesfully saved as {0}".format(log.name))

奇怪的是,程序正常运行并输出以下内容(我已经运行了几次)

pi@raspberrypi ~/clockpi $ sudo python3 filetest.py
Log succesfully saved as 6.log
pi@raspberrypi ~/clockpi $ sudo python3 filetest.py
Log succesfully saved as 7.log
pi@raspberrypi ~/clockpi $ sudo python3 filetest.py
Log succesfully saved as 8.log
pi@raspberrypi ~/clockpi $ 

但是我的Raspberry Pi上的〜/ log目录中没有任何内容。 更奇怪的是,通过复制粘贴到Python Interpreter中来执行同一脚本会产生以下内容

>>> import os    
>>> 
>>> os.makedirs(os.path.expanduser('~/logs'), exist_ok=True)
>>> os.chdir(os.path.expanduser('~/logs'))
>>> filenumber = 0
>>> while (os.path.isfile("{0}.log".format(filenumber))):
...     filenumber = filenumber + 1
... log = open('{0}.log'.format(filenumber), mode='a', encoding='utf-8')
  File "<stdin>", line 3
    log = open('{0}.log'.format(filenumber), mode='a', encoding='utf-8')
      ^
SyntaxError: invalid syntax
>>> log.close
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'log' is not defined
>>> print("Log succesfully saved as {0}".format(log.name))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'log' is not defined

但是〜/ log文件夹是正常创建的。 有人可以向我解释为什么该脚本无法按预期运行以及如何解决该问题吗? 感谢您的时间。

您可以不使用sudo尝试运行该程序吗?

我猜想当您使用sudo命令时,您将进入超级用户的上下文,该用户的主目录与当前用户的主目录不同,因此您看到在/root/logs创建了日志文件。

暂无
暂无

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

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