可以将文本文件的内容转储到一个 Python 列表中吗?

huangapple go评论72阅读模式
英文:

It is possible to dump content of a text file into a Python list?

问题

我有一个包含50个txt文件的目录。我想将每个文件的内容合并到一个Python列表中。

每个文件的内容如下:

line1
line2
line3

我正在使用以下代码将文件/文件路径放入一个列表中。我只需要循环遍历file_list并将每个txt文件的内容附加到列表中。

from pathlib import Path

def searching_all_files():
    dirpath = Path(r'C:\num')
    assert dirpath.is_dir()
    file_list = []
    for x in dirpath.iterdir():
        if x.is_file():
            file_list.append(x)
        elif x is_dir():
            file_list.extend(searching_all_files(x))
    return file_list

但我不确定最佳方法。

也许循环类似于这个的内容?

注意:这不是真正的代码!只是从空中抓取的想法。问题不是如何修复这个问题。我只是展示这个作为一个思路。欢迎所有方法。

file_path = Path('.....')
with open(file_path) as f:
    source_path = f.read().splitlines()
source_nospaces = [x.strip(' ') for x in source_path]
return source_nospaces

希望这对你有所帮助。

英文:

I have a directory of 50 txt files. I want to combine the contents of each file into a Python list.

Each file looks like;

line1
line2
line3

I am putting the files / file path into a list with this code. I just need to loop through file_list and append the content of each txt file to a list.

from pathlib import Path


def searching_all_files():
    dirpath = Path(r'C:\num')
    assert dirpath.is_dir()
    file_list = []
    for x in dirpath.iterdir():
        if x.is_file():
            file_list.append(x)
        elif x.is_dir():
            file_list.extend(searching_all_files(x))
    return file_list

But I am unsure best method

Maybe loop something close to this?

NOTE: NOT REAL CODE!!!! JUST A THOUGHT PULLED FROM THE AIR. THE QUESTION ISNT HOW TO FIX THIS. I AM JUST SHOWING THIS AS A THOUGHT. ALL METHODS WELCOME.

file_path = Path(r'.....')
    with open(file_path) as f:
        source_path = f.read().splitlines()
    source_nospaces = [x.strip(' ') for x in source_path]
    return source_nospaces

答案1

得分: 3

你可以利用pathlib.rglob来递归搜索目录中的所有文件,并使用readlines()将内容追加到列表中:

from pathlib import Path
files = Path('/tmp/text').rglob('*.txt')
res = []
for file in files:
    res += open(file).readlines()
print(res)

输出:

['file_content2\n', 'file_content3\n', 'file_content1\n']
英文:

You could make use of pathlib.rglob in order to search for all files in a directory recursively and readlines() to append the contents to list:

from pathlib import Path
files = Path('/tmp/text').rglob('*.txt')
res = []
for file in files:
    res += open(file).readlines()
print(res)

Out:

['file_content2\n', 'file_content3\n', 'file_content1\n']

huangapple
  • 本文由 发表于 2023年2月18日 07:06:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75489988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定