【问题标题】:IOError: [Errno 2] No such file or directoryIOError: [Errno 2] 没有这样的文件或目录
【发布时间】:2015-05-26 13:40:14
【问题描述】:

我正在尝试将所有种子文件的一些信息添加到我的 MySQL 数据库表的路径中,但似乎我有一些 PATH 问题。 正如你所看到的,有完整的路径,它甚至可以检测到“charlie.torrent”,所以我真的不明白问题出在哪里。

这是我的代码:

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

我真的不明白我的脚本的以下输出:

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'

我已经看过其他相同的主题,但没有任何结果。

【问题讨论】:

  • 你需要with open(path + file, 'rb') as torrentfile:
  • @heinst,请记住 path + file 是一个简单的串联。如果路径是/home/user/torrents,那么path + file 会给你/home/user/torrentscharlie.torrent。它也是相对特定于平台的,因此您必须修改 Unix 样式路径与 Windows 样式路径的代码。这就是 os.path.join 出现的地方,因为它会考虑正确的路径分隔符(尽管它不会修改 path 本身)。

标签: python python-2.7 path ioerror


【解决方案1】:

您正在尝试打开位于 path 中的文件,但不包括该路径,该路径会尝试在 Python 脚本的当前工作路径中打开该文件。例如,如果您从/home/user/script.py 运行脚本,而您的种子位于/home/user/torrents。当您执行open(file, 'rb') 时,您正在执行/home/user/charlie.torrent 而不是/home/user/torrents/charlie.torrent。尝试将with open(file, 'rb') 替换为with open(os.path.join(path, file), 'rb')

【讨论】:

    【解决方案2】:

    您也可以将当前所在的目录更改为路径。

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

    应该也可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      相关资源
      最近更新 更多