Store one specific line from a txt file? Python

There is something I am confused about and it is how I can store one line from a file and just use that one line, not all of the lines.

For example if I had a txt file:

3 4
happy maria
sad jake
angry honey
happy mary

where 3 represented the number of moods and 4 represents the number of people.

How would I then ONLY take 3 and 4 out of the file and store it so I could use it when I need it? For example numMood = 3 and numPeople = 4

I am not expecting anyone to code anything for me! I just am hoping someone could push me into the right direction or give me an idea.

Is the only way to store it into a dictionary and use the split() function?

6

2 Answers

Very similar to nexus66. I just called int on the results and used tuple expansion to put the values into parameters.

file_path = r'dummy.txt'
with open(file_path, 'rb') as file: first_line = file.readline()
numMood, numPeople = [int(x) for x in first_line.strip().split()]
print(numMood)
print(numPeople)

output

3
4
1

The easy way is using readline().

For example, let's assume your file is called my_file.

So you, first of all you should open your file, then read only the first line of it and print/return/save the first line of it which is 3 4. Then you can use split(" ") the spaces. But remember the ending of character of the return to the line which is \n you can replace it with an empty string using strip().

Like this example:

with open("my_file", 'r') as f: data = f.readline().strip().split(" ") print(data, type(data)) print("numMood = {0}\nnumPeople= {1}".format(data[0], data[1]))

Output:

['3', '4'] <class 'list'>
numMood = 3
numPeople= 4
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like