简体   繁体   中英

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.

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. Even more strangely, executing the same script by copy pasting into the Python Interpreter yields the following

>>> 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. 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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