Home > Net >  read the elements of a text in python
read the elements of a text in python

Time:12-15

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?

CodePudding user response:

Array = []
with open('input.txt','r') as f:
   #contents = f.read()
   Array = f.readlines()
   print(contents)

CodePudding user response:

try this:

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

CodePudding user response:

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)

CodePudding user response:

This is the code you want.

    with open("./input.txt",'r') as file:
        elements = [line.rstrip('\n') for line in file]
    print(elements)

CodePudding user response:

import pandas as pd

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

print(My_list)
  • Related