首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python [WinError 3]系统找不到指定的路径

Python [WinError 3]系统找不到指定的路径
EN

Stack Overflow用户
提问于 2022-11-21 15:34:47
回答 1查看 35关注 0票数 1

起初,这个脚本运行良好,但在它显示错误后,"[WinError 3] The system cannot find the path specified"没有更改脚本中的任何内容。

代码语言:javascript
复制
import os

paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables')

def files_with_word(word:str, paths:list) -> str:
    for path in paths:
        with open(path, "r") as f:
            if word in f.read():
                yield path


for filepath in files_with_word("Admin", paths):
    print(filepath)

我尝试卸载所有python并用python 3.11 64 bit重新安装它仍然不能工作。

EN

回答 1

Stack Overflow用户

发布于 2022-11-22 05:20:12

你所面临的问题就像没有使用绝对路径。paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables')只会得到一个没有路径信息的文件名列表。因此,如果您在同一目录中没有实际运行python文件,它将生成该文件未找到的错误。

在for循环中,我只是将源目录和文件名放在一起,以获得打开的完整路径。您还需要筛选出目录,因为当前代码还会尝试将目录作为文件打开并导致错误。

代码语言:javascript
复制
import os

src = r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables'
files = os.listdir(src)


# only get files. filter out directories 
files = [f for f in files if os.path.isfile(src+'/'+f)] 


def files_with_word(word:str, files:list) -> str:
    for file in files:
        # create full path to file
        full_path = src + "\\" + file
       
        #open using full path
        print(full_path)
        with open(full_path, "r") as f:
            if word in f.read():
                yield file


for filepath in files_with_word("Admin", files):
    print(filepath)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74521325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档