【问题标题】:"FileNotFoundError:[Errno 2] No such file or directory in windows" on constructed path构造路径上的“FileNotFoundError:[Errno 2] Windows 中没有此类文件或目录”
【发布时间】:2019-01-05 19:55:24
【问题描述】:

我的文件路径是

C:/Users/Ratul/Downloads/Machine_Learning_Data/reddit_data/reddit_data/

该目录中有许多文件夹。我需要查看那些目录并打开以“RC_”开头的文件

这是我的代码:

import sqlite3
import json
import os
from datetime import datetime

timeframe = '2015-05'
sql_transaction = []

connection = sqlite3.connect('{}.db'.format(timeframe))
c = connection.cursor()

def create_table():
    c.execute("CREATE TABLE IF NOT EXISTS parent_reply(parent_id TEXT PRIMARY KEY, comment_id TEXT UNIQUE, parent TEXT, comment TEXT, subreddit TEXT, unix INT, score INT)")

def format_data(data):
    data = data.replace('\n',' newlinechar ').replace('\r',' newlinechar ').replace('"',"'")
    return data

def find_parent(pid):
    try:
        sql = "SELECT comment FROM parent_reply WHERE comment_id = '{}' LIMIT 1".format(pid)
        c.execute(sql)
        result = c.fetchone()
        if result != None:
            return result[0]
        else: return False
    except Exception as e:
        #print(str(e))
        return False


if __name__ == '__main__':
    create_table()
    row_counter = 0
    paired_rows = 0

    with open('C:/Users/Ratul/Downloads/Machine_Learning_Data/reddit_data/reddit_data/{}/RC_{}'.format(timeframe.split('-')[0],timeframe), buffering=1000) as f:
        for row in f:
            row_counter += 1
            row = json.loads(row)
            parent_id = row['parent_id']
            body = format_data(row['body'])
            created_utc = row['created_utc']
            score = row['score']
            comment_id = row['name']
            subreddit = row['subreddit']
            parent_data = find_parent(parent_id)
            # maybe check for a child, if child, is our new score superior? If so, replace. If not...

            if score >= 2:
                existing_comment_score = find_existing_score(parent_id)

但路径似乎有些错误。我收到一个错误

Traceback(最近一次调用最后一次):文件 "C:/Users/Ratul/AppData/Local/Programs/Python/Python37/test02.py", 第 36 行,在 使用 open('C:/Users/Ratul/Downloads/Machine_Learning_Data/reddit_data/reddit_data/{}/RC_{}'.format(timeframe.split('-')[0],timeframe), buffering=1000) 作为 f : FileNotFoundError: [Errno 2] 没有这样的文件或 目录: 'C:/Users/Ratul/Downloads/Machine_Learning_Data/reddit_data/reddit_data/2015/RC_2015-05'

我不确定我在那里做错了什么。请帮忙。

【问题讨论】:

    标签: python windows python-3.x operating-system


    【解决方案1】:

    使用How to debug small programs (#1)

    print('C:/Users/Ratul/Downloads/Machine_Learning_Data/reddit_data/reddit_data/{}/RC_{}'.format(
           timeframe.split('-')[0],timeframe))
    

    而不是open。检查是否全部存在 - 因为对于您的某些值它不存在。因此错误。

    如果您的大部分文件都存在,则处理错误本身要容易得多:

    myname = 'C:/Users/Ratul/Downloads/Machine_Learning_Data/reddit_data/reddit_data/{}/RC_{}'.format(timeframe.split('-')[0],timeframe)
    
    try:
        with open(myname, buffering=1000) as f:
            for row in f:
                row_counter += 1
                row = json.loads(row)
                parent_id = row['parent_id']
                body = format_data(row['body'])
                created_utc = row['created_utc']
                score = row['score']
                comment_id = row['name']
                subreddit = row['subreddit']
                parent_data = find_parent(parent_id)
                # maybe check for a child, if child, is our new score superior? If so, replace. If not...
    
                if score >= 2:
                    existing_comment_score = find_existing_score(parent_id)
    except FileNotFoundError as fnfError:
        print(myname)
        print(fnfError)
    

    open() 命令不关心你使用\/ - 如果使用\ 你应该转义它或使用原始字符串(又名:r'C:\some\dir\file.txt') - 你的语法没问题 - open() 会在windows下使用合适的目录分隔符,即使你给它'c:/somedir/file.txt'

    阅读:About error handling

    【讨论】:

    • 我试过你的代码,它说没有这样的文件或目录,但我有目录,从屏幕截图可以看出。
    • 错误信息到底是什么,打印为myname。如果您将myname 内容复制/粘贴到资源管理器中并尝试导航到那里的文件会发生什么?
    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2021-08-24
    相关资源
    最近更新 更多