Home > Mobile >  When trying to read a file and print it, it returns an empty list
When trying to read a file and print it, it returns an empty list

Time:01-09

I am trying to read the contents of a file that I previously added to, and I want to append it to a list and print that to the console. When I run, it only prints empty lists. The file that I want it to read from only has 6 rows of 7 periods, with no spaces in between.

Here is my code:

list = []

def write():
    with open("board.txt", "w") as x:
        for each in range(6):
            x.write("......"   "\n")
        start("board.txt")

def start(x):
    with open(x) as f:
        for line in f:
            b = line.read()
            c = b.strip()
            x = list.append(c)
        print(list)

write()

And here is the output:

[]

Here is what the file (board.txt) looks like:

.......
.......
.......
.......
.......
.......

Please help, I’m new to code and this is really frustrating.

CodePudding user response:

The start("board.txt") has to be a tab or 4 spaces further to the left or the file wasn't closed correctly. And please do not overwrite built-ins. Global variables that change aren't a good idea.

def write():
    with open("board.txt", "w") as x:
        for each in range(6):
            x.write("......"   "\n")
    start("board.txt")

def start(x):
    array = []
    with open(x) as f:
        for line in f:
            array.append(line.strip())
        print(array)

write()

CodePudding user response:

I think this is problematic:

def start(x):
    with open(x) as f:
        for line in f:
            b = line.read()
            c = b.strip()
            x = list.append(c)
        print(list)

line is the content of a line in f - so the file. But you use line as a handler for a file - while it is a string with the content of a file - in this case ".......". Second - from where comes list? You print it. I would do what you want like this:

def write(filename="board.txt"):
    with open(filename, "w") as fout:
        for each in range(6):
            fout.write("......"   "\n")


def read(filename="board.txt"):
    with open(filename) as fin:
        return [line for line in fin] # or: fin.readlines()

write()
read()
  •  Tags:  
  • Related