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.py145 chars9 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.py138 chars9 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