0% found this document useful (0 votes)
2 views

Lab7_PythonFileHandling

Uploaded by

ALI BOUANANI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab7_PythonFileHandling

Uploaded by

ALI BOUANANI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

ENSA-Kenitra Module : Compétence Numériques

Lab 7: Python Text Files Handling

Exercise 1: Basic File Operations (Text Files)

Write a Python program that:

1. Creates a file named simple_file.txt if it doesn't already exist.

2. Writes three lines of text to the file using write(), where each line includes a person's
name and age, separated by a comma (e.g., Sarah,25).

3. Reads the file using read() and prints the entire content.

4. Appends 2 more lines of 2 persons and their age using writelines().

5. Reads and prints only the first two lines of the file using readline().

6. Uses files’ exception handling

Exercise 2: Comprehensive File Operations (Text Files)

Write a Python program that:

1. Creates a file named records.txt if it doesn't already exist.

2. Writes five lines of text to the file, where each line contains a student's name, age, and
grade, separated by a comma (e.g., Ali,20,16).

3. Adds three additional lines: one empty line and two lines containing special characters
(e.g., one line containing ### and another line @@@).

4. Reads the file using read() and prints the content.

5. Appends two more student records to the file, by asking the user to input these new
records.

6. Reads and prints only the second and fourth lines using readline().

7. Reads and prints only the lines that contain valid student records (ignoring the empty
lines and special character lines (having # and @)).

8. Deletes the file records.txt after all operations are complete. The program needs to
check if the file exists before performing deletion.

Ensure that you use exception handling to manage potential errors, such as issues with
file access, missing files, or permission errors.

Pr. Mehdia AJANA Chapter6 – Python: File Handling 1

You might also like