Read and Write Text Files Using Python

For example, there is such a Text file, as shown in the figure below. We need to read the data and then save the data to different folders in different directories.

The Python code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import os

# Read data in Text
students_data = []
with open('./data.txt', 'r') as f:
line = f.readline()
while line:
print(line)

line_data = line.split(',')

# Skip the first line
if line_data[0] == 'name':
line = f.readline()
continue

# Read the data of current row
curr_student_info = {}
curr_student_info["name"] = str(line_data[0])
curr_student_info["id"] = str(line_data[1])
curr_student_info["score"] = float(line_data[2])
curr_student_info["ranking"] = float(line_data[3])
students_data.append(curr_student_info)

# Continue reading the next line of data
line = f.readline()

# Save the data in different files
for curr_info in students_data:
path = "./student_data/" + str(curr_info["name"])
os.makedirs(path)

f_temp = open('./student_data/' + str(curr_info["name"]) + '/info.txt', 'w')
f_temp.write("id: " + str(curr_info["id"]) + "\n")
f_temp.write("score: " + str(curr_info["score"]) + "\n")
f_temp.write("ranking: " + str(curr_info["ranking"]) + "\n")
f_temp.close()

The data in Text can be read through the above code, as shown below:

1
2
3
4
5
6
7
name,id,score,ranking

A,S1001,100,1

B,S1002,90,2

C,S1003,80,3

And the generated files looks like this: