1

I have a text file like this:

enter image description here

there is no separation mark. When I use these lines of code, it returns nothing:

with open('input.txt','r') as f:
   contents = f.read()
   print(contents)

How can I save its elements in a python list or array?

Mitra
  • 157
  • 2
  • 12
  • The issue is with the formatting of your "input.txt" file. You could inspect it to see if it actually is a text file and that you can edit the numbers in notepad. There is nothing wrong with your code. – It works on my pc Dec 14 '21 at 11:38

5 Answers5

2
Array = []
with open('input.txt','r') as f:
   #contents = f.read()
   Array = f.readlines()
   print(contents)
M Z G
  • 41
  • 3
2

try this:

    with open("./input.txt",'r') as file:
    for line in file:
        print(line)
1

My input_numbers.txt looks as follows:

1 2 3
4 5 6
7 8 9

To parse it as a list of ints, you can use the following approach:

import itertools
with open("input_numbers.txt", "r") as f:
    res = list(itertools.chain.from_iterable(list(map(int, x.split(" "))) for x in f))

print(res)

PS: Note that the question you asked is How can I save its elements in a python list or array?, not how can I print it to screen (despite what your code tries to do)

nikeros
  • 3,302
  • 2
  • 10
  • 26
0
import pandas as pd

Data = pd.read_csv('input.txt')
My_list = []
for line in Data:
    My_list.append(line)

print(My_list)
RiveN
  • 2,595
  • 11
  • 13
  • 26
ASH
  • 31
  • 5
0

This is the code you want.

    with open("./input.txt",'r') as file:
        elements = [line.rstrip('\n') for line in file]
    print(elements)
Kedar U Shet
  • 538
  • 2
  • 11