1

So I'm currently in a path to learn code, and I'm currently doing small/beginner projects to get familiar with the python language.

Normally I can get my way around by searching what I want...

But this time I'm stuck.

What I want to do is for most of you really simple... I want to open a .txt file (code for the file creation is allready there) read a specific line of the .txt and assign it to a variable, this variable is later used to compare with another user input variable...

Sorry if it's not very clear.

Update:

so this is as far as i come...

with open('infos.txt', 'r') as f:
    lines = f.readlines()

user_master = lines[0]
print(user_master) # this gives the output that i want: "test"

if user_master == "test":
    print("OK") # This does not work, no output on the console... 
Daniel
  • 11
  • 2

2 Answers2

0

You can use .readlines() to get all the lines and get the line you want by indexing:

with open('myfile.txt', 'r') as f:
    lines = f.readlines()

line = lines[INDEX].strip()
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
0

The problem is because each line in the list returned from readlines() has a trailing newline, so the if user_master == "test" fails. The simplest fix is create the list of lines without the ends yourself by utilizing the built-in str,splitlines() method:

with open('infos.txt', 'r') as f:
    lines = f.read().splitlines()  # Create list of lines with newlines stripped.

user_master = lines[0]
print(user_master) # -> test

if user_master == "test":
    print("OK") # This now works.
martineau
  • 119,623
  • 25
  • 170
  • 301