Show List

Python File I/O

File I/O in Python allows you to read from and write to files on your computer.

Here is an example of how to open a file and read its contents in Python:

python
Copy code
# Open a file for reading with open("example.txt", "r") as file: # Read the contents of the file contents = file.read() print(contents)

In this example, the open function is used to open the file example.txt in read mode (indicated by the "r" argument). The with statement is used to ensure that the file is properly closed after the block of code is executed, even if an exception is raised.

Here is an example of how to write to a file in Python:

python
Copy code
# Open a file for writing with open("example.txt", "w") as file: # Write to the file file.write("Hello, world!")

In this example, the open function is used to open the file example.txt in write mode (indicated by the "w" argument). The with statement is used to ensure that the file is properly closed after the block of code is executed, even if an exception is raised. If the file does not exist, it will be created. If the file already exists, its contents will be overwritten.

You can also append to an existing file by opening it in append mode ("a").

Here is an example of how to read a file line by line in Python:

python
Copy code
# Open a file for reading with open("example.txt", "r") as file: # Iterate over the lines of the file for line in file: print(line)

In this example, the for loop is used to iterate over the lines of the file. The file object behaves like a list of lines, so you can iterate over it using a for loop.


    Leave a Comment


  • captcha text