簡體   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