简体   繁体   English

Python打印不完整的数据

[英]Python print incomplete data

I have the following data in raw_data.txt我在 raw_data.txt 中有以下数据

id=001;name=Johan Strauss;address=58 Jalan Jelutong, 11600 Pulau Pinang, Malaysia;gender=male
id=002;name=Jennifer Teng;address=Q-2-4,Desa Indah, Lorong Minyak, 13000 Kedah, Malaysia;gender=female

I ran the following code:我运行了以下代码:

f = open('raw_data.txt', 'r')
for x in f:
x = x.replace("id","Student",)
x = x.replace("name","Name")
x = x.replace("address","Home Number")
x = x.replace("gender","Gender")
x = x.replace(";","\n")
print (x)

g = open('formatted.txt','a')
g.write(x)

This is the output I got in formatted.txt这是我在 formatted.txt 中得到的输出

Student=002
Name=Jennifer Teng
Home Number=Q-2-4,Desa Indah, Lorong Minyak, 13000 Kedah, Malaysia
Gender=female

I lost student 001 data.我丢失了学生 001 的数据。 What is wrong with my code?我的代码有什么问题?

Problem: you are writing to file in the end only once but processing more student data in the for loop before.问题:您最终只写入一次文件,但之前在 for 循环中处理了更多学生数据。 The x variable only stores the final value and writes the student 002 data only. x 变量只存储最终值,只写入学生 002 数据。

with open('data.txt', 'r') as f: # reading all data line by line from the raw_data.txt
    data = f.readlines()
    
with open('formatted.txt', 'w') as f: # writing data to new file student by student
    for student in data:
        student = student.strip().replace("id","Student").replace("name","Name").replace("address","Home Number").replace("gender","Gender").replace(";","\n")
        f.write(student)
        print(student)

File output screenshot文件输出截图

Remember to close the file that you opened.请记住关闭您打开的文件。 Your code has an indentation problem that the for loop iterates line by line.您的代码有一个缩进问题,for 循环逐行迭代。 The corrected code can be corrected as follows:修正后的代码可以修正如下:

f = open('raw_data.txt', 'r')
y=''
for x in f:
    x = x.replace("id","Student")
    x = x.replace("name","Name")
    x = x.replace("address","Home Number")
    x = x.replace("gender","Gender")
    x = x.replace(";","\n")
    y=y+x #Used to store the newly formated text of each line
print(y)
f.close()
g = open('formatted.txt','a')
g.write(y) #Write the updated information to the file
g.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM