[英]Python - How can I separate characters and integers from a string into sub-strings?
[英]Python: How do I separate a mix of strings and integers from a csv?
import os
import csv
import pandas as pd
import itertools
data = r"C:\Users\chase\Documents\Exercise\MA Exercise_20190328-2"
for root, dirs, files in os.walk(data):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
df = open("PikesPeak_Males.txt", "r")
if df.mode == "r":
contents = df.read()
print(contents)
with open("PikesPeak_Males.txt", "r") as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
with open("PikesPeak_Males.csv", "w") as out_file:
writer = csv.writer(out_file)
writer.writerow(("Place", "Div/Tot", "Number", "Name", "Age", "Hometown", "Gun Time", "Net Time", "Pace"))
writer.writerows(lines)
所以我有一個賽車手的運行時間數據集。 我將文本文件轉換為csv
但是,我想將所有數據拆分為以下列“Place”、“Div/Tot”、“Number”等......但我不知道該怎么做沒有任何逗號或功能來分割行。 主要目標是計算賽車手的平均跑步時間。 這是它現在的樣子:
我希望我的 csv 看起來如何的示例:
檢查 .txt 文件中的分隔符是什么。 如果它們是制表符,則在讀取 csv 時使用制表符作為分隔符:
pd.read_csv("filename.csv", header=None, delimiter=r"\t")
如果分隔符是空格的倍數,首先通過 .txt 文件將多個空格轉換為單個空格或其他一些字符(“\\t”、“、”、...),然后使用所選字符作為分隔符.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.