![](/img/trans.png)
[英]Python: How can I read in the characters from a line in a file and convert them to floats and strs, depending on if they are numbers or letters?
[英]How can I read a file and convert the data to numbers?
我正在嘗試讀取一個包含
1,2 20000
並可能讀取具有相同類型的其他文本文件,只有更多的數字,例如:
1,2,3 30000 或 2,3,4,5 2000000。
with open('coordinate.txt','r') as file:
for line in file:
line = line.strip()
pieces = line.split()
data.append(pieces)
然后分配coord = data[0]
和trial = data[1]
但 coord 變為["1,2"]
我只是不知道如何通過去掉逗號並制作 numpy 形式來分隔 1 和 2。 如何正確讀取文件並將其分配為我想要的格式?
更簡單的方法是使用split
方法:
pieces = []
lines = None
with open('cooridnate.txt', 'r') as fp:
lines = fp.readlines() # Get lines
for line in lines:
splitted_line = line.rstrip().split(',') # Split line with "," as a delimiter
pieces.append({
'coord': int(splited_line[0]),
'trial': splitted_line[1:]
}) # Append the splitted in pieces
print(pieces)
您可能還需要創建一個循環進行試用(如果您也想轉換它)。 是你要找的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.