practical notes file handling

Python File Handling

Python File Handling

To open and handle files in Python, you can follow the steps below:

  1. Open a File

    Use the open() function, specifying the filename and mode:

    file = open('filename', 'mode')
  2. Specify the Mode

    Choose a mode, such as ‘r’ for reading or ‘w’ for writing.

  3. Reading or Writing to the File

    To read or write, use:

    content = file.read()
    file.write('Hello, world!')
  4. Close the File

    Don’t forget to close the file when done:

    file.close()

Here is an example of file handling in Python:

# Writing to a file
with open('hello.txt', 'w') as f:
    f.write('Hello, world!')

# Reading from a file
with open('hello.txt', 'r') as f:
    content = f.read()
    print(content)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top