简体   繁体   English

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

[英]How do I concatenate the folder and the file name with a forward slash?

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)

I need to search the files in input path and locate the word Superman and then print the location where the word was found.我需要搜索输入路径中的文件并找到超人一词,然后打印找到该词的位置。 I cannot get the concatenation to work along with the.read_text().我无法让连接与 the.read_text() 一起工作。

This is the output:这是 output:

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

Any help would be greatly appreciated.任何帮助将不胜感激。

os.listdir returns a list of strings so you can check like: os.listdir返回一个字符串列表,因此您可以像这样检查:

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

if you want to check the content of your file you can use:如果你想检查你的文件的内容,你可以使用:

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))
folder = Path(folder_path)

myfiles = os.listdir(folder)

for file in myfiles:
   file_path = Path.join(folder, file)
   print(file_path) # Here you can perform file_path.read_text()

Hope this helps.希望这可以帮助。 The code is self explanatory.代码是不言自明的。 So I am skipping the explanation.所以我跳过了解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM