open file and read line in python

To open a file in python, you can use the open() function. The open() function takes two arguments, the file name and the mode in which you wish to open the file.

Mode | Description ---- | ----------- 'r' | Open a file for reading (default) 'w' | Open a file for writing. Creates a new file if it does not exist, overwrites the existing file if it does. 'a' | Open a file for appending. The file pointer is at the end of the file if it exists. Creates a new file if it does not exist.

To read a file line by line, you can use a for loop to loop through each line and print it.

Here is an example:

main.py
# open file in read mode
file = open("example.txt", "r")

# loop through each line in the file
for line in file:
    print(line)

# close the file
file.close()
160 chars
10 lines

In the above example, we first open the file "example.txt" in read mode using the open() function. Then, we use a for loop to loop through each line in the file and print it. Finally, we close the file using the close() method.

gistlibby LogSnag