Python导入模块加载\u sou

2024-09-29 21:25:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我对装货来源有疑问。你知道吗

当我的2.py文件位于同一目录/home/pi时,它们工作正常。你知道吗

你知道吗主.py你知道吗

 #!/usr/bin/python
import buttonlog

你知道吗按钮日志你知道吗

import datetime
i = datetime.datetime.now()

#OPEN FILE & APPEND
f=open('buttonlog.txt','a')
#WRITE DATE THEN NEW LINE WITH THE '\N'
f.write(i.isoformat() + '\n')

当我运行python时主.py它写的条目和我期望的一样。 但是我想将main.py存储在另一个目录中,所以我尝试了这个方法,它存储在/home/pi/test

#!/usr/bin/python
import imp
imp.load_source('buttonlog', '/home/pi/buttonlog.py')

当我运行python /home/pi/test/main.py时,我不会得到任何错误,也不会将条目写入我的文件。我做错什么了?你知道吗


Tags: 文件pytestimport目录homedatetimebin
1条回答
网友
1楼 · 发布于 2024-09-29 21:25:08

秘密是使用open命令。你知道吗

文件上说第一个论点

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

通过只传递"buttonlog.txt",这不是绝对路径名,因此它是相对于当前工作目录的。你知道吗

解决这个问题的最简单方法是使用完整路径。如果您总是希望它写入/home/pi,您只需要:

f=open('/home/pi/buttonlog.txt','a')

还有其他的选择,尽管我认为这是最干净的。在为相同的结果发出open命令之前,还可以更改当前的工作目录。只需将此代码放在open行上方:

import os
os.chdir("/home/pi")

相关问题 更多 >

    热门问题