python - 如何使用正斜杠连接文件夹和文件名?
问题描述
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)
我需要在输入路径中搜索文件并找到超人这个词,然后打印找到这个词的位置。我无法让连接与 .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 - 在 python 中制作不和谐机器人时,预计会出现缩进块错误
- javascript - JQuery 事件只触发一次
- javascript - 无法在“节点”上执行“附加孩子”:参数 1 不是“节点”类型,无法拖放 div
- django - Django 中的 MultipleObjectsReturned 错误,但我希望返回多个对象
- python - 来自for循环的嵌套字典将相同的值添加到所有嵌套键
- python - 在python中返回两个值的函数
- python - 循环直到语句为真
- c# - 如何下载我通过 Restlet Client 在我的代码中设置的名称的 pdf
- c++ - 康威的生命游戏帮助我理解这个意想不到的输出
- python - 如何解决 Python 属性错误-“str”对象没有属性“balance_inventory”