-4

How can i code a function that can read a text file append it into a list thank in advance. i tried this but it won't work .

def readdata (z):
x=[ ]
for dig in open(z).readlines():
    digx=dig.strip().split(" ")
    if len(dig) == 0:
        print 
        return 0

    else :
        return x.append(str(digx))
        print x
 readdata (r'C:\Users\Administrator\Coding\Python\Text\Day5\scores.txt')
  • 1
    In assembly, I presume. – Pavel Anossov Jun 30 '13 at 18:39
  • What do you want in the list? A list entry per line? – Maxime Chéramy Jun 30 '13 at 18:40
  • What kind of list? I doubt I read "and doesn't call another function or code" right, as this means you want it to happen magically. Nothing happens magically in programming. – Sumurai8 Jun 30 '13 at 18:40
  • 1
    The negative votes reflect the fact that you should do some basic research before posting a question on StackExchange. Read the FAQ and welcome to the community! – Codie CodeMonkey Jun 30 '13 at 18:43
  • Also, a really good tip (if I say so myself!) Use pdb.set_trace() at the start of your script and walk through it. You'll have to import pdb at the start. You can read about pdb, or its more visual cousins such as pudb, winpdb, etc. online. – Codie CodeMonkey Jun 30 '13 at 19:10

1 Answers1

2

This is a two-liner in Python

with open("myfile.txt") as file:
    lines = file.readlines()

lines is then a list of the lines of the file. Each will end with a '\n' (newline) character, except possibly the last line.

Codie CodeMonkey
  • 7,669
  • 2
  • 29
  • 45
  • 3
    why not just `lines=list(file)` if you are just gonna store it in memory anyway there isnt much call for a generator – Joran Beasley Jun 30 '13 at 18:48
  • @JoranBeasley True! I'm just in the habit of using generators because I rarely store intermediate results. But yes, for the OP's question your suggestion is more concise. – Codie CodeMonkey Jun 30 '13 at 19:05