Question

Question:

How can I open a file in python that contains one integer value per line. Make python read the file, store data in a list and then print the list?

I have to ask the user for a file name and then do everything above. The file entered by the user will be used as 'alist' in the function below.

Thanks

def selectionSort(alist):
    for index in range(0, len(alist)):
        ismall = index
        for i in range(index,len(alist)):
            if alist[ismall] > alist[i]:
                ismall = i
        alist[index], alist[ismall] = alist[ismall], alist[index]
    return alist  

No correct solution

OTHER TIPS

I think this is exactly what you need:

file = open('filename.txt', 'r')
lines = [int(line.strip()) for line in file.readlines()]
print(lines)

I didn't use a with statement here, as I was not sure whether or not you intended to use the file further in your code.


EDIT: You can just assign an input to a variable...

filename = input('Enter file path: ')

And then the above stuff, except open the file using that variable as a parameter...

file = open(filename, 'r')

Finally, submit the list lines to your function, selectionSort.

selectionSort(lines)

Note: This will only work if the file already exists, but I am sure that is what you meant as there would be no point in creating a new one as it would be empty. Also, if the file specified is not in the current working directory you would need to specify the full path- not just the filename.

Easiest way to open a file in Python and store its contents in a string:

with open('file.txt') as f:
  contents = f.read()

for your problem:

with open('file.txt') as f:
  values = [int(line) for line in f.readlines()]
print values

Edit: As noted in one of the other answers, the variable f only exists within the indented with-block. This construction automatically handles file closing in some error cases, which you would have to do with a finally-construct otherwise.

You can assign the list of integers to a string or a list

file = open('file.txt', mode = 'r')
values = file.read()

values will have a string which can be printed directly

file = open('file.txt', mode = 'r')
values = file.readlines()

values will have a list for each integer but can't be printed directly

f.readlines() read all the lines in your file, but what if your file contains a lot of lines?

You can try this instead:

new_list = [] ## start a list variable

with open('filename.txt', 'r') as f:
    for line in f:
        ## remove '\n' from the end of the line
        line = line.strip()

        ## store each line as an integer in the list variable
        new_list.append(int(line)) 

print new_list
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top