简体   繁体   English

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

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

I have this python script that creates a home folder and then writes a new file #.log every time it is run. 我有这个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))

Strangely, the program proceeds normally and outputs the following(I've run it a few times) 奇怪的是,程序正常运行并输出以下内容(我已经运行了几次)

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 $ 

But theres nothing in the ~/log directory on my Raspberry Pi. 但是我的Raspberry Pi上的〜/ log目录中没有任何内容。 Even more strangely, executing the same script by copy pasting into the Python Interpreter yields the following 更奇怪的是,通过复制粘贴到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

But the ~/log folder is created normally. 但是〜/ log文件夹是正常创建的。 Can someone explain to me why the script does not work as expected and how I can fix it? 有人可以向我解释为什么该脚本无法按预期运行以及如何解决该问题吗? Thank you for your time. 感谢您的时间。

Can you try running the program without using sudo. 您可以不使用sudo尝试运行该程序吗?

I am guessing when you are using sudo command, you are going into the context of the super user , which has a different home directory than your current user, hence you are seeing the log files getting created in /root/logs . 我猜想当您使用sudo命令时,您将进入超级用户的上下文,该用户的主目录与当前用户的主目录不同,因此您看到在/root/logs创建了日志文件。

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

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