Python IOError:[Errno 2]没有这样的文件或目录
我试图在MySQL数据库的一个表的路径中添加所有torrents文件的一些信息,但似乎我有一些路径问题。 正如你所看到的,有完整的路径,它甚至检测到“charlie.torrent”,所以我真的不明白问题出在哪里 这是我的代码: 我真的不明白我脚本的以下输出:Python IOError:[Errno 2]没有这样的文件或目录,python,python-2.7,path,ioerror,Python,Python 2.7,Path,Ioerror,我试图在MySQL数据库的一个表的路径中添加所有torrents文件的一些信息,但似乎我有一些路径问题。 正如你所看到的,有完整的路径,它甚至检测到“charlie.torrent”,所以我真的不明白问题出在哪里 这是我的代码: 我真的不明白我脚本的以下输出: root@debian:/home/florian/Documents/mysite/polls# python bdd.py Traceback (most recent call last): File "bdd.py", li
root@debian:/home/florian/Documents/mysite/polls# python bdd.py
Traceback (most recent call last):
File "bdd.py", line 17, in <module>
with open(file, 'rb') as torrentfile:
IOError: [Errno 2] No such file or directory: 'charlie.torrent'
root@debian:/home/florian/Documents/mysite/polls#python bdd.py
回溯(最近一次呼叫最后一次):
文件“bdd.py”,第17行,在
打开(文件“rb”)作为torrentfile:
IOError:[Errno 2]没有这样的文件或目录:“charlie.torrent”
我已经查看了其他相同的主题,但没有任何结果。您正在尝试打开位于
路径中的文件,但不包括该路径,该路径尝试在Python脚本的当前工作路径中打开该文件。例如,如果您从/home/user/script.py
运行脚本,而您的torrents位于/home/user/torrents
中。当您打开(文件'rb')
时,您所做的是/home/user/charlie.torrent
,而不是/home/user/torrents/charlie.torrent
。尝试将替换为open(文件'rb')
替换为替换为open(os.path.join(路径,文件),'rb')
您还可以将当前所在的目录更改为path
...
dirs = os.listdir(path)
os.chdir(path)
for file in dirs:
...
这也应该起作用。您需要使用open(path+file,'rb')作为torrentfile:@heinst,请记住,
path+file
是一个简单的连接。如果路径为/home/user/torrents
,则路径+文件
将为您提供/home/user/torrentsharlie.torrent
。它也是相对特定于平台的,因此您必须修改Unix样式路径与Windows样式路径的代码。这就是os.path.join
的作用,因为它将解释正确的路径分隔符(尽管它不会修改path
本身)。
...
dirs = os.listdir(path)
os.chdir(path)
for file in dirs:
...