Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top