[英]How to convert data from txt files to CSV files using python
I have a text file It is just a small example , but the real one is pretty similar.我有一个文本文件这只是一个小例子,但真实的非常相似。
and I want to know how to convert the TXT file to "CSV File" like this using Python?我想知道如何使用 Python 将 TXT 文件转换为“CSV 文件” ?
Read the text file contents into a list called lines.将文本文件内容读入名为行的列表中。
text_file_path = r'some file path'
lines = []
with open(text_file_path, 'r') as f:
lines = f.readlines()
You now have a list with each line in it as a string.您现在有一个列表,其中的每一行都是一个字符串。
Create another list with the numbers for the rows.使用行号创建另一个列表。
rows = range(1, len(lines))
Now combine them as a pandas dataframe with the desired column headings and save it to csv.现在将它们组合为 pandas dataframe 与所需的列标题并将其保存到 csv。
import pandas as pd
csv_path = r'csv file path'
df = pd.DataFrame([rows, lines], columns = ['sr. no.', 'client'])
df.to_csv(csv_path, index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.