gpt4 book ai didi

python - 如何用正斜杠连接文件夹和文件名?

转载 作者:行者123 更新时间:2023-12-01 06:20:54 25 4
gpt4 key购买 nike

from pathlib import Path
import os

folderpath = input("What is the absolute path to Superman's folder?")

mypath = Path(folderpath)

mypath = os.listdir(folderpath)
for files in mypath:
print ("Found one of Superman's's files..." + files)
#up to here, the code is good

for read in byfiles:
byfiles = ('mypath\\files')
byfiles.read_text()
if "Superman" in read:
print("Found Superman in file " + read)

我需要搜索输入路径中的文件并找到单词 Superman,然后打印找到该单词的位置。我无法让连接与 .read_text() 一起工作。

这是输出:

What is the absolute path to Superman's folder?C:\Users\OneDrive\Documents\Superman_files
Found one of Superman's files...boring_document.txt
Found one of Superman's files...eggs.txt
Found one of Superman's files...hello.txt
Found one of Superman's files...secret_document.txt
Found one of Superman's files...spam.txt

任何帮助将不胜感激。

最佳答案

os.listdir 返回一个字符串列表,以便您可以检查:

for read in mypath:
if "Superman" in read:
print("Found Superman in file " + read)

如果您想检查文件的内容,可以使用:

from pathlib import Path


folderpath = input("What is the absolute path to Superman's folder?")
mypath = Path(folderpath)

for child in mypath.iterdir():
if child.is_file():
with open(child, 'r') as file:
if "Superman" in file.read():
print("Found Superman in file ", child.relative_to(mypath))

关于python - 如何用正斜杠连接文件夹和文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60364354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com