Home > front end >  Read file names from text file and print to list using python
Read file names from text file and print to list using python

Time:03-18

I want to read a text file which contains list of file names and append that to a list.

I have written the code, but the output is repeated twice.

For example, there is text file named filelist.txt which contains the list of files (ex:- mango.txt).

When I run the code its printing mango.txt twice.

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

CodePudding user response:

Print line instead

        for line in lines:
            print(line) 

CodePudding user response:

It's a one-liner:

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

CodePudding user response:

You error is to print lines instead of line in your for loop

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:

mango.txt
hello.csv
  • Related