1

So, I need to use a notepad file for inputs.

I can open the file and print the numbers out but can't seem to assign each line of the notepad to a variable that I can work with in the code

file = open(r"C:/Users/aryaa/Desktop/Base.txt", "r")
text = file.read()
print (text)

I need to put input in a notepad file in different lines (e.g line 1 - 3, lines 2 - 7 etc). I need to place these lines to a variable in python code and work with them all from a note pad file. So how would I open a notepad file and assign each line in the notepad file to a variable that I can work within python?

CypherX
  • 7,019
  • 3
  • 25
  • 37

1 Answers1

0

It's not clear exactly what you want, but this will read your file and use the text in each line as a key that can map to some value.

import random

line_dict = {}

file = open(r"sampleLines", "r")
lines = file.readlines()
for line in lines:
    var = line.strip()# get rid of \n
    line_dict[var] = random.randint(1,6)

print(line_dict)

My script just assigns a random int value from 1 to 6 to each 'line' in the file. You will need to have some collection in your python script to hold 1. the text of the file line, and 2. the value that you request from the user.

my file has these lines:

cat sampleLines 
apple
banana
cherry

and produces this output:

$ python script.py 
{'apple': 4, 'banana': 3, 'cherry': 4}
shanecandoit
  • 581
  • 1
  • 3
  • 11