Ask coding questions

← Back to all posts
get input in a txt file python
DavidSafro (19)

So in a competition that I recently partook we had to write a piece of code where in a txt file you would get two long strings of numbers and our code had to find the longest amount of digits that repeated in both sequences. For example 2930566649 and 234066639 the output would be 666. Anyway I have the code down, I'm just confused how can python get input from a txt file?

Answered by Muffinlavania (1518) [earned 5 cycles]
View Answer
Muffinlavania (1518)

Well i dont know if you want input() in a text file, or if you just want to read the number in a text file, but ill show both
Lets say you want the numbers in your text file to show up
the text file is:


you can do this to get the contents in a string:

f=open('f.txt','r') #text is now a string form of all the contents in f.txt
f.close() #closing files cause they tend to break if you dont

2) Getting code from a text file
this one is kinda weird, since it uses eval() and idk if it would even work, but the idea goes like this:

f=open('f.txt','r') #text is now 'input()'
eval(text) #should take input?