open a file in python

To open a file in Python, you can use the built-in function open(). Here's an example of how to use it to read a file:

main.py
# Open a file for reading
file = open('example.txt', 'r')

# Read the contents of the file
contents = file.read()

# Close the file
file.close()
145 chars
9 lines

In this example, 'example.txt' is the name of the file we want to open, and 'r' tells Python that we want to open the file for reading. We then use the read() method to read the contents of the file into the contents variable. Finally, we close the file with the close() method.

To open a file for writing, you can use the same open() function, but with the 'w' mode instead:

main.py
# Open a file for writing
file = open('example.txt', 'w')

# Write to the file
file.write('Hello, world!')

# Close the file
file.close()
138 chars
9 lines

In this example, we're opening 'example.txt' for writing, and then using the write() method to write the string 'Hello, world!' to the file.

gistlibby LogSnag