Как объединить папку и имя файла с форвардом sla sh? - PullRequest
1 голос
/ 23 февраля 2020
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

Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

1 голос
/ 23 февраля 2020

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))
0 голосов
/ 23 февраля 2020
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()

Надеюсь, это поможет. Код не требует пояснений. Поэтому я пропускаю объяснение.

...