Search code examples
pythonpython-2.7pathioerror

IOError: [Errno 2] No such file or directory


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.


Solution

  • 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').