0

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?

naraemee
  • 45
  • 1
  • 1
  • 8
  • read the line and then process it however you want, store the results however you want. it's not really clear what you're asking – pvg Dec 06 '16 at 02:21
  • 1
    simple `readline()`, and later `split()` and `int()` – furas Dec 06 '16 at 02:22
  • Sorry if it wasn't clear! I'm trying to find the best way to explain it, but what I'm trying to ask is if there is any way you can choose specific lines of a txt file and use that data. What if later I wanted to use data from only line 2, or data from lines 2-4. Is there any way I can do that? – naraemee Dec 06 '16 at 02:28
  • You should update your question so. My actual answer don't fill your new request. – Chiheb Nexus Dec 06 '16 at 02:34
  • So sorry for the trouble nexus66! – naraemee Dec 06 '16 at 02:36
  • Possible duplicate of [Read lines containing integers from a file in Python?](http://stackoverflow.com/questions/11354544/read-lines-containing-integers-from-a-file-in-python) – pvg Dec 06 '16 at 03:28

2 Answers2

3

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
Alex O
  • 118
  • 7
0

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
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
  • 1
    `.strip()` removes the line break at the end of the string, `.replace("\n", "").strip()` is redundant. Also, `.split(" ")` and `.split()` are not equivalent, and the OP probably wants `.split()`. – DYZ Dec 06 '16 at 02:36