IOError: [Errno 2] No such file or directory

匿名 (未验证) 提交于 2019-12-03 02:28:01

问题:

I'm trying to add some informations of all the torrents file in a path to a Table of my MySQL database but it seems like i have some PATH problems. As you can see there is the full path and it even detect the "charlie.torrent" so i don't really understand what is the problem.

This is my code:

#!/usr/bin/env python # -*- coding: utf-8 -*-  import mysql.connector import bencode import binascii import hashlib import os import sys  conn = mysql.connector.connect(host="localhost",user="root",password="root", database="TORRENTS") cursor = conn.cursor path = "/home/florian/TorrentFiles" dirs = os.listdir(path) for file in dirs:         try:                 with open(file, 'rb') as torrentfile:                         torrent = bencode.bdecode(torrentfile.read())                         user = ("torrent['info']['name']","torrent['info']['length'],'bytes'","(hashlib.sha1(bencode.bencode(torrent['info'])).hexdigest())")                         cursor.execute("""INSERT INTO torrent_infos (Name, Size, Hash) VALUES(%s, %s, %s)""", user)         except bencode.BTL.BTFailure:                 continue   conn.close() 

And i really don't understand the following output of my script:

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' 

I already had a look to the others same subjects without any result.

回答1:

You're trying to open a file located in path, but not including that path, which tries to open the file in the current working path of your Python script. For example, if you run the script from /home/user/script.py, while your torrents are in /home/user/torrents. When you do open(file, 'rb') you are doing /home/user/charlie.torrent as opposed to /home/user/torrents/charlie.torrent. Try replacing with open(file, 'rb') with with open(os.path.join(path, file), 'rb').



回答2:

You could also change the directory you are currently in to path.

... dirs = os.listdir(path) os.chdir(path) for file in dirs: ... 

That should work also.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!