简体   繁体   English

从python文件路径列表中加载文件

[英]Load files from a list of file paths in python

I have a text file with a couple hundred file paths to text files which I would like to open, write / cut up pieces from it and save under a new name. 我有一个文本文件,其中有数百个指向文本文件的文件路径,我想打开它们,从中写入/剪切内容,并以新名称保存。

I've been Googling how to do this and found the module glob, but I can't figure out exactly how to use this. 我一直在谷歌搜索如何做到这一点,并找到了模块glob,但我不知道到底该如何使用它。

Could you guys point me in the right direction? 你们能指出我正确的方向吗?

If you have specific paths to files, you won't need to glob module. 如果您有文件的特定路径,则不需要glob模块。 The glob module is useful when you want to use path like /user/home/someone/pictures/*.jpg . 当您要使用/user/home/someone/pictures/*.jpg路径时,glob模块非常有用。 From what I understand you have a file with normal paths. 据我了解,您有一个具有正常路径的文件。

You can use this code as a start: 您可以使用以下代码作为开始:

with open('file_with_paths', 'r') as paths_list:
    for file_path in paths_list:
        with open(file_path, 'r') as file:
            # Do what you want with one of the files here.

You can just traverse the file line by line and then take out what you want from that name. 您可以逐行遍历文件,然后从该名称中取出所需内容。 Later save/create it . 以后保存/创建它。 Below sample code might help 下面的示例代码可能会有所帮助

with open('file_name') as f:
    for file_path in f:
        import os
        file_name = os.path.basename(file_path)
        absolute path = os.path.dirname(file_path)
        # change whatever you want to with above two and save the file
        # os.makedirs to create directry
        # os.open() in write mode to create the file

Let me know if it helps you 让我知道是否对您有帮助

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

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