Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将文件名添加到每个文件读入的最后一行?_Python_Python 3.x_Dataframe_Import_Glob - Fatal编程技术网

Python 如何将文件名添加到每个文件读入的最后一行?

Python 如何将文件名添加到每个文件读入的最后一行?,python,python-3.x,dataframe,import,glob,Python,Python 3.x,Dataframe,Import,Glob,我有一组逐行读取的文件。我希望在每个文件的最后一行旁边有文件名。这是完成文件部分读取的代码,但我不知道如何显示文件名: import glob a = [] def convert_txt_to_dataframe(path): for files in glob.glob(path + "./*manual.txt"): for x in open(files): a.append(x) 这就完成了逐行导入所有文本文件,所以现在我希望每个文

我有一组逐行读取的文件。我希望在每个文件的最后一行旁边有文件名。这是完成文件部分读取的代码,但我不知道如何显示文件名:

import glob

a = []

def convert_txt_to_dataframe(path):
    for files in glob.glob(path + "./*manual.txt"):
        for x in open(files):
            a.append(x)
这就完成了逐行导入所有文本文件,所以现在我希望每个文件的最后一行旁边都有一个附带的文件名

我希望它看起来像:

你好,再见
0感谢您成为忠诚的客户。MyDocuments/TextFile1
谢谢你是个糟糕的顾客。MyDocuments/TextFile1
谢谢你是个好顾客。MyDocuments/TextFile3

所以我假设您正在获取一个文件列表,您提到的[0,1,2]列是指列表中每个文件的最后一行。考虑到这一点,我将尝试一种更简单的方法,而不是数据帧。即使您出于其他原因不得不使用数据帧,您也可以将转换为文本作为最后一步,并尝试以下操作:

Example File ("ExampleText2"):
I love coffee
I love creamer
I love coffee and creamer
I have a rash..
代码:

输出:

最后 “我出疹子了。。其他文件名'


readlines()将返回文件中所有行的列表,因此您可以尝试调用-1来提取最后一行,然后添加到其中

我假设行数大于或等于文件数

import glob

words = ['Thank you for being a loyal customer.',
         'Thank you for being a horrible customer.',   
         'Thank you for being a nice customer.']    

def convert(path):
    a = []
    z = 0
    for files in glob.glob(path + "/*.txt"):
        temp = [words[z],files]
        a.append(temp)
        z += 1
    print (a)    

convert(your_path)

这个问题定义不清,但假设OP想要数据帧示例中显示的结果(即,不只是最后一行以某种方式用文件名修饰,而是所有行都用文件名修饰),这里有一种实现方法。对于本例,我们只有两个文件:
file1.txt
包含两行:'a'和'b',
file2.txt
包含一行:'c'

我们编写一个文件读取器,返回列表列表:每个子列表包含文件名和一行

import glob

def get_file(filename):
    with open(filename) as f:
        return [[filename, line.rstrip('\n')] for line in f]
试试看:

m = map(get_file, glob.glob('file*.txt'))
list(m)

Out[]:
[[['file2.txt', 'c']], [['file1.txt', 'a'], ['file1.txt', 'b']]]
让我们将这些列表展平,得到一个二维数组。此外,如果文件按字母顺序排序,可能会得到更好的结果

def flatten(m):
    return [k for sublist in m for k in sublist]

m = map(get_file, sorted(glob.glob('file*.txt')))
flatten(m)

Out[]:
[['file1.txt', 'a'], ['file1.txt', 'b'], ['file2.txt', 'c']]
现在,它有时有助于获得行号(比如说,如果我们要将数据放入数据框中,并进行进一步的排序和分析)。我们的读者变成:

def get_file(filename):
    with open(filename) as f:
        return [[filename, lineno, line.rstrip('\n')] for lineno, line in enumerate(f, start=1)]

m = map(get_file, sorted(glob.glob('file*.txt')))
out = pd.DataFrame(flatten(m), columns=['filename', 'lineno', 'line'])
out

Out[]:
    filename  lineno line
0  file1.txt       1    a
1  file1.txt       2    b
2  file2.txt       1    c
请注意,如果我们有大量文件,上面的
映射
非常适合多线程阅读:

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=4) as pool:
    m = pool.map(get_file, sorted(glob.glob('file*.txt')))
    out = pd.DataFrame(flatten(m), columns=['filename', 'lineno', 'line'])
out

Out[]:
    filename  lineno line
0  file1.txt       1    a
1  file1.txt       2    b
2  file2.txt       1    c

你能用一个例子来说明你到底想要实现什么吗?那么
a[-1]+=files
for x in..
循环之后?@Martihn Pieters,你能写出完整的代码吗?这样我就能完全理解你的意思了?@Srini,我添加了我想查看的输出。很抱歉,我仍然无法理解所需的输出。你好和再见是什么?0,1,2是否表示3个不同文件的最后一行?
from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=4) as pool:
    m = pool.map(get_file, sorted(glob.glob('file*.txt')))
    out = pd.DataFrame(flatten(m), columns=['filename', 'lineno', 'line'])
out

Out[]:
    filename  lineno line
0  file1.txt       1    a
1  file1.txt       2    b
2  file2.txt       1    c