infile = open("myfile.txt", "r") in python

To read a file in Python, you can use the open() function with the file name and mode ("r" for reading) as arguments. Once the file is opened, you can read its contents using various methods like read(), readline(), or readlines().

Here's an example of how to use open() to read a file:

main.py
# open file for reading
infile = open("myfile.txt", "r")

# read entire file contents
file_content = infile.read()

# print file contents
print(file_content)

# close the file
infile.close()
191 chars
12 lines

In the code above, we opened the file myfile.txt in read mode using open(), read its entire contents into a variable file_content using read(), printed the contents, and finally closed the file using close(). It's important to close the file after you're done reading or writing to it, to ensure that any changes you made to it are saved and to free up system resources.

gistlibby LogSnag