read input from a txt file in python

To read input from a txt file in python, you can use the "open" function to open the file, followed by the "read" function to read the contents of the file. Here's an example:

main.py
with open('input_file.txt', 'r') as file:
    input_text = file.read()
71 chars
3 lines

In the above example, input_file.txt is the text file that you want to read. The with open statement automatically closes the file after reading. The read function reads the entire contents of the file as a string and stores it in the input_text variable.

If you want to read the file line by line, you can use the readlines function instead:

main.py
with open('input_file.txt', 'r') as file:
    input_lines = file.readlines()
77 chars
3 lines

In this case, input_lines is a list of strings, where each string represents a line from the input file.

related categories

gistlibby LogSnag