简体   繁体   English

使用 python 从文本文件读取文件名并打印到列表

[英]Read file names from text file and print to list using python

I want to read a text file which contains list of file names and append that to a list.我想读取一个文本文件,其中包含文件名列表和 append 列表。

I have written the code, but the output is repeated twice.我已经写了代码,但是 output 重复了两次。

For example, there is text file named filelist.txt which contains the list of files (ex:- mango.txt).例如,有一个名为 filelist.txt 的文本文件,其中包含文件列表(例如:- mango.txt)。

When I run the code its printing mango.txt twice.当我运行代码时,它打印 mango.txt 两次。

def im_ru(filelist1):
    with open(filelist1,"r") as fp:
        lines = fp.read().splitlines()
        for line in lines:
            print(lines) 

You error is to print lines instead of line in your for loop您的错误是在for循环中打印lines而不是line

Use:利用:

def im_ru(filelist1):
    with open(filelist1, 'r') as fp:
        # You have to remove manually the end line character
        lines = [line.strip() for line in fp]
    return lines

Usage:用法:

>>> im_ru('data.txt')
['mango.txt', 'hello.csv']

Content of data.txt : data.txt的内容:

mango.txt
hello.csv

Print line instead改为打印line

        for line in lines:
            print(line) 

It's a one-liner:这是一个单线:

from pathlib import Path
filenames = Path("filelist.txt").read_text().splitlines()

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

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