使用文本文件中列出的路径在Python中获取文件数据

发布于 2025-02-07 09:10:44 字数 637 浏览 1 评论 0原文

目前,我的脚本正在工作。它可以提取数据,但仅使用绝对路径,我需要对其进行修改以使其在获得路径时使其通用。

我有一个计划修改脚本,可以简单地将文件的路径添加到.txt文件中,并且脚本将其读取为目录以获取文件并提取其内容,但是我需要帮助来弄清楚我需要的内容要在我的脚本上使用它来使它起作用,有人可以帮助我吗?

import requests

path = "/home/admin/files/myfiles.txt"
with open(path, 'r') as f:
    line = f.read().rstrip()
    print(line)

myfiles.txt 包含目录

/home/admin/files/test1.txt
/home/admin/files/test2.txt
/home/admin/files/test3.txt

这些目录是文件的路径,一旦我执行python文件,我需要提取数据的路径,它将在列出的文件上提取数据(test1,test1,test2,test3)。 txt)并将其作为文本发送到电报。

当前,这是可以读取路径的修改脚本。

如果您需要更多细节,请告诉我。

Currently, my script is working. It can extract data but with an absolute path only, I need to modify it to make it universal when it comes to getting the path.

I have a plan to modify my script that can simply add the path of the files into the .txt file and the script will read it as a directory to get the file and extract its content, but I need help to figure out what I need to use on my script to make it work, is there someone can help me?

import requests

path = "/home/admin/files/myfiles.txt"
with open(path, 'r') as f:
    line = f.read().rstrip()
    print(line)

myfiles.txt contains directories

/home/admin/files/test1.txt
/home/admin/files/test2.txt
/home/admin/files/test3.txt

these directory are path of the files that I need to extract the data once I execute the python file it will extract data on the file listed (test1,test2,test3.txt) and send it to telegram as text.

Currently, this is the modified script that can read the path.

If you need more details let me know.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱你不解释 2025-02-14 09:10:44

它包含文件的路径,我的计划是当我在.txt文件中添加多个文件路径时,python脚本将其读取为目录并获取文件。

如果我让您正确,您正在寻找readlines方法来读取文件路径列表。

path = "/home/admin/files/myfiles.txt"

with open(path, 'r') as fp:
    filepaths = fp.readlines()

for filepath in filepaths:
    with open(filepath, 'r') as file:
        # do something with file
        content = file.read()

it contains path of the files and my plan is when I add a multiple file path in the .txt file the python script will read it as directory and get the file.

If I get you right you are looking for readlines method to read the list of files' paths.

path = "/home/admin/files/myfiles.txt"

with open(path, 'r') as fp:
    filepaths = fp.readlines()

for filepath in filepaths:
    with open(filepath, 'r') as file:
        # do something with file
        content = file.read()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文