戳人痛处

导航

python读取每行以逗号分隔的文本的的方法

import turtle as t
t.title('自动绘制轨迹')
t.setup(800,600,0,0)
t.pencolor("red")
t.pensize(5)

def tprint(a):
    t.pencolor(a[3],a[4],a[5])
    t.fd(a[0])
    if a[1]:
        t.right(a[2])
    else:
        t.left(a[2])

f = open("t.txt")
data= list()
for line in f:
    if len(line) == 1:
        break;
    data = line.replace("\n","") #去掉每一行的换行
    #print(data)
    data = eval(data)   #转换为元组
    #print(data)
    #print(data[0])
    tprint(data)    #元组传参
f.close()

#以下为t.txt文本文件内容
300,0,144,1,0,0
300,0,144,0,1,0
300,0,144,0,0,1
300,0,144,1,1,0
300,0,108,0,1,1
184,0,72,1,0,1
184,0,72,0,0,0
184,0,72,0,0,0
184,0,72,0,0,0
184,1,72,1,0,1
184,1,72,0,0,0
184,1,72,0,0,0
184,1,72,0,0,0
184,1,72,0,0,0
184,1,720,0,0,0

 

后记--------------------

现在是2021\10\30;

python不说精通,但也算灵活运用了;

 

二种版本=

示例文本

文本.txt

11,12,13
21,22,23
31,32,33
41,42,43
one,two,three

code

file = open('文本.txt')
all_data=[]
for line in file:
    temp = line.split(',')
    all_data.append(temp)
print('-----------------------------')
try:
    print(all_data)
    print(all_data[0])
    print(all_data[-1][0])
except:
    pass
all_data.clear()
print('=============================')
file.seek(0)
for line in file.readlines():
    temp = line.replace('\n',"").split(',') #去掉换行 以逗号分隔
    all_data.append(temp)
try:
    print(all_data)
    print(all_data[0])
    print(all_data[-1][0])
except:
    pass
print('----------------------------')
if int(all_data[0][0])==11:
    print(all_data[0])

控制台打印

PS E:\python\python> & "E:/Program Files/Python38/python.exe" e:/python/python/python_all_by_me/文本处理/分割字符.py
-----------------------------
[['11', '12', '13\n'], ['21', '22', '23\n'], ['31', '32', '33\n'], ['41', '42', '43\n'], ['one', 'two', 'three']]
['11', '12', '13\n']
one
=============================
[['11', '12', '13'], ['21', '22', '23'], ['31', '32', '33'], ['41', '42', '43'], ['one', 'two', 'three']]
['11', '12', '13']
one
----------------------------
['11', '12', '13']

 

posted on 2020-12-23 10:49  戳人痛处  阅读(4093)  评论(0编辑  收藏  举报