2015-05-26 57 views
2

我想在我的MySQL數據庫的表的路徑中添加一些山洪文件的一些信息,但它似乎我有一些路徑問題。 正如你可以看到有完整的路徑,它甚至檢測到「charlie.torrent」,所以我真的不明白是什麼問題。IOError:[Errno 2]沒有這樣的文件或目錄

這是我的代碼:

#!/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() 

,我真的不明白我的腳本的輸出如下:

[email protected]:/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' 

我已經有了一看別人相同的主題沒有任何結果。

+4

你需要用openfile(path + file,'rb')作爲torrentfile:' – heinst

+0

@heinst,記住'path + file'是一個簡單的連接。如果路徑是'/ home/user/torrents',那麼'path + file'會給你'/ home/user/torrentscharlie.torrent'。它也是相對平臺特定的,所以你必須修改Unix風格路徑與Windows風格路徑的代碼。這是'os.path.join'進來的地方,因爲它會解釋適當的路徑分隔符(儘管它本身不會修改路徑)。 – paidhima

回答

5

您試圖打開位於path中的文件,但不包括該路徑,該路徑會嘗試在您的Python腳本的當前工作路徑中打開該文件。例如,如果您從/home/user/script.py運行腳本,而您的種子在/home/user/torrents。當你做open(file, 'rb')你正在做/home/user/charlie.torrent而不是/home/user/torrents/charlie.torrent。嘗試用with open(os.path.join(path, file), 'rb')替換with open(file, 'rb')

0

您也可以將您當前所在的目錄更改爲路徑。

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

這也應該工作。

相關問題