0

I can't seem to figure out how to use values given in a text file and import them into python to create a list. What I'm trying to accomplish here is to create a gameboard and then put numbers on it as a sample set. I have to use Quickdraw to accomplish this - I kind of know how to get the numbers on Quickdraw but I cannot seem to import the numbers from the text file. Previous assignments involved getting the user to input values or using an I/O redirection, this is a little different. Could anyone assist me on this?

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
user1840501
  • 5
  • 2
  • 3
  • 1
    Look at the builtin [open](http://docs.python.org/3.2/library/functions.html#open) for starters – Jon Clements Nov 21 '12 at 20:32
  • 1
    Show us what you've tried so that we can point out where you're going wrong – inspectorG4dget Nov 21 '12 at 20:38
  • 1
    Your question is hard to understand. What exactly have you tried, and which part are you having a problem with implementing? – user4815162342 Nov 21 '12 at 20:38
  • This is what I have so far then: for i in range (0, Board_size): sys.stderr.write("Enter Game Values:") gamevalues = float(input()) # To get the values from the text file using I/O datalist = [gamevalues] # To define the values entered as a list print ("color 0 0 0") print (datalist) print ("fill text", x, y) The quickdraw stuff I can work out, it is the list that is giving me nightmares. – user1840501 Nov 21 '12 at 20:44
  • You are allowed to edit your answer (there's a bit marked `edit` under the tags)- it makes it much easier for everyone to see your posted code, rather than in a comment – Jon Clements Nov 21 '12 at 22:34

2 Answers2

3

Depends on the contents of the file you want to read and output in the list you want to get.

# assuming you have values each on separate line
values = []
for line in open('path-to-the-file'):
    values.append(line)
    # might want to implement stripping newlines and such in here
    # by using line.strip() or .rstrip()

# or perhaps more than one value in a line, with some separator
values = []
for line in open('path-to-the-file'):
    # e.g. ':' as a separator
    separator = ':'
    line = line.split(separator)
    for value in line:
        values.append(value)

# or all in one line with separators
values = open('path-to-the-file').read().split(separator)
# might want to use .strip() on this one too, before split method

It could be more accurate if we knew the input and output requirements.

moon.musick
  • 5,125
  • 2
  • 23
  • 23
1

Two steps here:

  • open the file

  • read the lines

This page might help you: http://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

BoppreH
  • 8,014
  • 4
  • 34
  • 71