Я пытаюсь преобразовать текстовый файл в CSV в Python. Входной текстовый файл выглядит следующим образом:
Employee Name: Dr.john doe
Designation: Professor
Email: johndoe@google.com
ContactNo: 1234567, 9999999
Qualification: M.Tech., Ph.D.
Area of Interest / Specialisation: network security
Employee Name: Dr. john doe2
Designation: Professor2
Email: johndoe2@google.com
ContactNo: 222222222
Qualification: B.Tech., Ph.D.
Area of Interest / Specialisation: network security2
Employee Name: Dr. john doe3
Designation: Associate Professor3
Email: johndoe3@google.com
ContactNo: 333333,4444444
Qualification: Ph.D.
Area of Interest / Specialisation: network security3
Designation: Associate Professor4
Email: johndoe4@google.com
ContactNo: 44444444 ,Intercom No.44444
Qualification: : M.Sc.
Designation: Programmer
Email: johndoe5@google.com
ContactNo: 5555555555 ,Intercom No.5555
Qualification: Ph.D |Computer Science
Designation: Computer Operator
Email: johndoe6@google.com
ContactNo: 666666666
Qualification: D.C.Sc. & E.,
Designation: Computer Operator
Email: johndoe7@google.com
ContactNo: 777777777 ,Intercom No.77777<
Qualification: D.E & TC.,
Designation: Instructor4
Email: johndoe8@google.com
ContactNo: 8888888888 ,Intercom No.8888
Qualification: D.C.Sc. & E.,`
Мне нужно в CSV в следующем формате
Employee name,designation,email,contact,Qualification,Specialisation
Dr. john doe,Professor,johndoe@google.com,1234567,B.E.,network security
Dr. john doe2,Professor,johndoe2@google.com,222222222,M.S.,network security2
Dr. john doe3,Associate,Professor3,johndoe3@gmail.com,333333,M.Tech.,network security3
iя пробовал это
with open('test.txt', 'r') as records:
stripped = (line.strip() for line in records)
lines = (line.split(":") for line in stripped if line)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerows(lines)
мой код выше дает следующий вывод, который имеет только две строки (я не знаю, как сделать 6 столбцов и добавить кортежи в строках):
Employee Name, Dr.john doe
Designation, Professor
Email, johndoe@google.com
ContactNo, 1234567, 9999999
Qualification, M.Tech., Ph.D.
Area of Interest / Specialisation, network security
Employee Name, Dr. john doe2
Designation, Professor2
Email, johndoe2@google.com
ContactNo, 222222222
Qualification, B.Tech., Ph.D.
Area of Interest / Specialisation, network security2
Employee Name, Dr. john doe3
Designation, Associate Professor3
Email, johndoe3@google.com
ContactNo, 333333,4444444
Qualification, Ph.D.
Area of Interest / Specialisation, network security3
вкратце: я могу разделить имя атрибута и его значение, но я не знаю, как заполнить значения в определенных полях.