簡體   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)

我需要搜索輸入路徑中的文件並找到超人一詞,然后打印找到該詞的位置。 我無法讓連接與 the.read_text() 一起工作。

這是 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

任何幫助將不勝感激。

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))
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()

希望這可以幫助。 代碼是不言自明的。 所以我跳過了解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM