Working with Files

Python provides built-in function to handle file manipulation from creating, reading to writing.

Reading Text Files

To read a text file in Python, you can use the built-in open() function with the desired file path and mode. The most common modes are:

  • 'r': read (default mode)
  • 'w': write
  • 'a': append
  • 'x': create (and write)

Here’s an example of reading a text file:

with open('file.txt', 'r') as file:
    data = file.read()
    print(data)

Writing Text Files

To write data to a text file, you can use the open() function with the 'w' (write) or 'a'(append) mode.

In this example, we write data to a file:

data = "This is a text file."

with open('file.txt', 'w') as file:
    file.write(data)

Example

Suppose you have a CSV file with user data that needs to be cleaned and transformed before being saved into a new file. The CSV file has the following columns: user_id, name, email, and age.

user_id,name,email,age
1,John Doe,[email protected],32
2,Jane Smith,[email protected],28
3,James Brown,[email protected],55

The following Python script reads the CSV file, removes all users aged below 30, and saves the new data into another file. We’ll use the build-in module csv.

import csv

input_file = 'users.csv'
output_file = 'filtered_users.csv'

with open(input_file, 'r') as infile, open(output_file, 'w', newline='') as outfile:
    csv_reader = csv.DictReader(infile)
    fieldnames = csv_reader.fieldnames

    csv_writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    csv_writer.writeheader()

    for row in csv_reader:
        if int(row['age']) >= 30:
            csv_writer.writerow(row)

Exercise Working with Files

!pip install rggrader
# @title #### Student Identity
student_id = "your student id" # @param {type:"string"}
name = "your name" # @param {type:"string"}
# @title #### 00. Read File
from rggrader import submit

# TODO: 
# 1. In Google Colab, navigate to the left sidebar and click on the file folder icon 📁. Create a new text file named 'output.txt' by right clicking in the file panel and selecting 'New File'.
# 2. Assume that you need to write the string "Hello, OpenAI!" to 'output.txt'. 
# 3. Write a Python code that opens 'output.txt' in write mode and writes this string to the file.
# 4. Assign the string "Hello, OpenAI!" to a variable named 'content'.

# Note: This exercise is for demonstrating that you know the appropriate Python code for writing to a file. The actual file writing won't occur.

# Put your code here:
file_content = ""


# ---- End of your code ----


# Do not modify the code below. It is used to submit your solution.
assignment_id = "06-working-with-files"
question_id = "00_read_file"
submit(student_id, name, assignment_id, file_content, question_id)

# Example:
# Assume File: 'data.txt'
# Content: "Data Science with OpenAI"
# Output: After reading and stripping, the content should be "Data Science with OpenAI"
Back to top