Python 10c - Split & Edit Files

Splitting a File

The split command is used to split up a line of a file into different parts.

The character or string in brackets after the split command is the value that will denote each split.

In the example below I have split the file at each comma. Remember that Python numbering starts at 0 so the first section is 0, not 1.





The program below splits each line of the file at each forward-slash ( ).

The printed statement is the employee's first name, surname and job position.






Practice Task 1

Create a file (new txt document in Notepad) called movies.

Type in the movie name, main actor, genre (e.g. horror), year it was released and your rating out of 10.

Print just the movie name and year it released.

Example solution:

Editing a File

Overwriting data in a file is a tricky process.

The program below uses the same Employees.txt file as above but allows the user to change the address of an employee.

A temporary file is created to store the lines of the employee file, but the line with the changes is replaced specifically with the new address.


I have explained each line of the program to the right: 

When I executed the program below I entered Thomas Wynne's details and changed his address.

When I opened the employees file the address had been updated:

1: Importing os allows me to rename and remove files later in the program.

3: Opens the employee file in read mode.

5 - 8: Input lines allow the user to enter the first name, surname and the person's new address.

10: A found flag is set up and set to False.

12: The for loop cycles through each line in the file.

13: Each line is split into separate parts from each /.

15: An if statement checks if the first name and surname match an employee in the file.

16: A replacement line is created by putting the original line together but with the new address.

18: The found flag is changed to True because the employee first name and surname matched.

19: A temporary file is created and opened in write mode.

20: The seek command restarts the file at line 0.

22: The for loop cycles through each line of the employee file from the beginning. If the first name and surname match it will write the new line to the file, otherwise it will rewrite the original line.

28 & 29: Both files are closed.

31 & 32: If the names didn't match, an appropriate message is printed.

34  - 37: If the address was changed, the original file is renamed and deleted and the temp file is renamed as the original file.

Practice Task 2

Use the movie file you created for practice task 1.

Ask the user to enter the name of a movie. Ask them to enter an updated rating out of 10.

Update the file to change the rating to the new value.

Example solution:

© CSNewbs 2020