4

For example I have a txt file:

3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7

On every line there are 4 numbers and there are 4 lines. At end of lines there's \n (except the last one). The code I have is:

f = input("Insert file name: ")
file = open(f, encoding="UTF-8")

What I want is the text file to become [[3,2,7,4],[1,8,9,3],[6,5,4,1],[1,0,8,7]].

I have tried everything, I know the answer is probably really simple, but I just really give up after an hour of attempts. Tried read(), readlines(), split(), splitlines(), strip() and whatever else I could find on the internet. So many can't even make a difference between them...

2
  • 1
    Always use with statement for opening the files. It will close the file object at the end of the block automatically. Beside, you should use consider using csv module which is more suitable for this case. Read your file with csv and it will gives you an iterable contain all lines splitted. Then list(reader_object) will give you the desire result. Commented Apr 15, 2017 at 10:28
  • 1
    looks like a duplicate, but not easy to find an original solving this. This is a good question because the title says it all, and the body is short & documented enough. Great first post. Commented Apr 15, 2017 at 10:39

4 Answers 4

4

Once you opened the file, use this one-liner using split as you mentionned and nested list comprehension:

with open(f, encoding="UTF-8") as file:   # safer way to open the file (and close it automatically on block exit)
    result = [[int(x) for x in l.split()] for l in file]
  • the inner listcomp splits & converts each line to integers (making an array of integers)
  • the outer listcomp just iterates on the lines of the file

note that it will fail if there are something else than integers in your file.

(as a side note, file is a built-in in python 2, but not anymore in python 3, however I usually refrain from using it)

Sign up to request clarification or add additional context in comments.

Comments

2

You can do like this,

[map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]

Line by line execution for more information

In [75]: print open('abc.txt').read()
3 2 7 4

1 8 9 3

6 5 4 1

1 0 8 7

split with newline.

In [76]: print open('abc.txt').read().split('\n')
['3 2 7 4', '', '1 8 9 3', '', '6 5 4 1', '', '1 0 8 7', '']

Remove the unnecessary null string.

In [77]: print filter(None,open('abc.txt').read().split('\n'))
['3 2 7 4', '1 8 9 3', '6 5 4 1', '1 0 8 7']

split with spaces

In [78]: print [i.split() for i in filter(None,open('abc.txt').read().split('\n'))]
[['3', '2', '7', '4'], ['1', '8', '9', '3'], ['6', '5', '4', '1'], ['1', '0', '8', '7']]

convert the element to int

In [79]: print [map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
[[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]

Comments

2

The following uses a list comprehension to create a list-of-lists. It reads each line from the file, splits it up using whitespace as a delimiter, uses the map function to create an iterator that returns the result of calling the int integer constructor on each of the string elements found in the line this way, and lastly creates a sub-list from that.

This process is repeated for each line in the file, each time resulting is a sub-list of the final list container object.

f = input("File name? ")
with open(f, encoding="UTF-8") as file:
    data = [list(map(int, line.split())) for line in file]
print(data)  # -> [[3, 2, 7, 4], [1, 8, 9, 3], [6, 5, 4, 1], [1, 0, 8, 7]]

1 Comment

Do you think you'd be able to add to the body of your answer to give a description of how your code functions?
0
with open('intFile.txt') as f:
    res = [[int(x) for x in line.split()] for line in f]
    with open('intList.txt', 'w') as f:
        f.write(str(res))

Adding to accepted answer. If you want to write that list to file, you need to open file and write as string as write only accepts string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.