Python/input output

FILE input , output

kimble2 2024. 8. 15. 08:08
반응형

File input and output in Python are crucial for reading from and writing to files. This is typically done using the open() function.

1. Opening a File

  • open() function: Used to open a file. This function takes the file path and the mode as arguments.
    • "r": Read mode (default)
    • "w": Write mode (overwrites the file if it exists, creates a new one if it doesn’t)
    • "a": Append mode (adds content to the end of the file)
    • "b": Binary mode (for binary files like images or videos)

Example:

 

file = open("example.txt", "r")  # Open the file in read mode

2. Reading from a File

  • read() function: Used to read the entire file.
  • readline() function: Reads the file line by line.
  • readlines() function: Reads all the lines of a file into a list.

Example:

 

file = open("example.txt", "r")  # Open the file
content = file.read()            # Read the entire content
print(content)                   # Print the content
file.close()                     # Close the file

3. Writing to a File

  • write() function: Used to write text to a file.

Example:

file = open("example.txt", "w")  # Open the file in write mode
file.write("Hello, World!\n")    # Write content to the file
file.write("This is a test.\n")  # Write additional content
file.close()                     # Close the file

 

Appending to a File

  • By using a mode, you can add data to the end of a file.

Example:

 

file = open("example.txt", "a")  # Open the file in append mode
file.write("This line is added.\n")  # Add content
file.close()                     # Close the file

 

5. Automatically Closing a File (Using the with statement)

To automatically handle opening and closing files, you can use the with statement, which ensures the file is closed once you are done with it.

Example:

 

with open("example.txt", "r") as file:
    content = file.read()        # Read the entire content
    print(content)               # Print the content
# The file is automatically closed after the with block ends.

6. Complete Example

Below is a complete example of writing data to a file and then reading it back.

 

# Writing data to a file
with open("example.txt", "w") as file:
    file.write("Hello, Python!\n")
    file.write("This is a file I/O example.\n")

# Reading data from the file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

This example demonstrates writing text to "example.txt" and then reading it back to display in the console.

 

 

반응형

'Python > input output' 카테고리의 다른 글

input , ouput  (0) 2024.08.15