-2

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
  • 3
  • 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
  • "I have written the code, but the output is repeated twice." In your own words: where the code says `print(lines)`, what do you think this means to do? What is the content of `lines` at this point in the program? How many times will this code run? (Hint: is it inside a loop? What is the purpose of loops?) What do you want to happen each time through the loop? (Hint: did you want to print some *other* value?) – Karl Knechtel Aug 29 '23 at 20:01

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
  • 109,409
  • 8
  • 28
  • 52
0

Print line instead

        for line in lines:
            print(line) 
DeGo
  • 783
  • 6
  • 14
0

It's a one-liner:

from pathlib import Path
filenames = Path("filelist.txt").read_text().splitlines()
suvayu
  • 4,271
  • 2
  • 29
  • 35