Python: Read Text File and Split File into List Variables, With Each Variable Having 4 Lines Each

Python 3, Read textfile and separate each line and fill in corresponding variables

Here's something that should work:

first we need to get all the lines read into a list.

>>> with open('in.txt', 'r') as f:
>>> lines = f.read().splitlines()

now we can index nicely in:

>>> print(lines[0])
John|Graham|JOB|AGE

Okay, now we want to split each line into the data we need.

>>> first = lines[0]
>>> info = first.split('|')
['John', 'Graham', 'JOB', 'AGE']

And then to put everything into a variable:

>>> NAME, LASTNAME, JOB, AGE = info
>>> print(NAME)
John
>>> print(LASTNAME)
Graham

Putting it all together:

with open('in.txt', 'r') as f:
lines = f.read().splitlines()

def get_info(lines, line_num):
line = lines[line_num]
return line.split('|')

NAME, LASTNAME, JOB, AGE = get_info(lines, 0)
print(NAME) # Prints "John"

If you don't want to read in the whole file at once, you can use the same techniques in your script:

with open(filename) as fp:
for i, line in enumerate(fp):
print(i)
print(line)
if i == index:
NAME, LASTNAME, JOB, AGE = line.split('|')
break

How can I attribute each line of a txt file to a variable?

Instead of having so many variables, a better solution would be to use a dictionary instead. So basically something like:

my_dictionary = {}

with open('sentences.txt', 'r') as file:
lines = file.readlines()
for line in lines:
my_dictionary[lines.index(line)] = line.strip()

print(my_dictionary)

So to access the line, you can just access the key of that dictionary, making your code efficient and clean :)

Making specific columns in a text file into a list

You could use pandas, it also fixes the scientific notation:

import pandas as pd

df = pd.read_csv('filename.txt', delim_whitespace=True, header=None, skiprows=3, skipfooter=4, engine='python')

Output df:























































01234
00.00.06371000.00.48438092001.0
10.00.06371000.00.46352822022.5
20.00.06371000.01.15874599999999981984.5
30.00.06371000.01.153131960.5
40.00.06371000.00.487392099999999941986.5

how to read multiple input data listed on the same line of a file in python

you can just use below code:

f = open('1.txt' , 'r')
lines = f.read().split(" ")

so you have list of values and you can take it in variable if you want like below:
a = lines[0], b = lines[1] and so on.

You can use a1,a2,a3 = f.read().split(" ") if you want it in variables. Provided you have exact number of variables as values in file.

Hope this helps.



Related Topics



Leave a reply



Submit