-1

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) 
msangel
  • 1
  • 2
  • Does this answer your question? [How to read a text file into a list or an array with Python](https://stackoverflow.com/questions/14676265/how-to-read-a-text-file-into-a-list-or-an-array-with-python) – depperm Mar 17 '22 at 10:54

3 Answers3

0

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
Corralien
  • 70,617
  • 7
  • 16
  • 36
0

Print line instead

        for line in lines:
            print(line) 
DeGo
  • 782
  • 7
  • 14
0

It's a one-liner:

from pathlib import Path
filenames = Path("filelist.txt").read_text().splitlines()
suvayu
  • 3,531
  • 25
  • 31