Python 3.x 我是python新手,我想从文本文件导入值和参数,并将其传递到我的函数中。我该怎么做?

Python 3.x 我是python新手,我想从文本文件导入值和参数,并将其传递到我的函数中。我该怎么做?,python-3.x,list,function,file-io,text-files,Python 3.x,List,Function,File Io,Text Files,我在网上阅读了一些资源,我知道我必须使用open(),但我该怎么做呢? 这是我应该使用它的地方 tmpl_1 = Template('X' **#arrowhead comes here from textfile**, [ Point(0, 0),# values from txtfile comes here Point(1, 1), Point(0, 1), Point(1, 0)]) tmpl_2 = Template('line', [ Poin

我在网上阅读了一些资源,我知道我必须使用open(),但我该怎么做呢? 这是我应该使用它的地方

tmpl_1 = Template('X' **#arrowhead comes here from textfile**, [
    Point(0, 0),# values from txtfile comes here
    Point(1, 1),
    Point(0, 1),
    Point(1, 0)])
tmpl_2 = Template('line', [
    Point(0, 0),
    Point(1, 0)])
文本文件的格式为:

arrowhead
BEGIN
28,85
110,80
118,80
127,80
135,80
141,80
147,80
152,80
156,80
160,80
162,80
164,80
165,80
165,80
END

我该怎么做呢?

以下是你该怎么做

f = open("demofile.txt", "r")
initial = f.readline() #gets your initial line arrowhead
points = list()
if f.readline() == "BEGIN":
    while(f.readline() != "END":
        point = f.readline()
        coordinates = point.split(",")
        points.append((int(coordinates[0]),int(coordinates[1])))
print(points) #tuples of all your points
试试这个:

with open('text_file.txt', 'r') as my_file:
    arwhead = my_file.readline() # this is the arrowhead
    print(arwhead) # this is the arrowhead
    splited_line = [line.rstrip().split(',') for line in my_file] # this will split every line in the text file as a separate list
    #print(splited_line)
    for i in range(len(splited_line)):
       if splited_line[i][0] != 'BEGIN':
           try:
              Point = (splited_line[i][0], splited_line[i][1])
              print(Point)
           except IndexError:
              pass
输出:

arrowhead

('28', '85')
('110', '80')
('118', '80')
('127', '80')
('135', '80')
('141', '80')
('147', '80')
('152', '80')
('156', '80')
('160', '80')
('162', '80')
('164', '80')
('165', '80')
('165', '80')
你可以这样做

In [18]: with open('test.txt') as f:
    ...:     lines = [line.rstrip() for line in f]
    ...:     for ele in lines[lines.index('BEGIN') + 1: lines.index('END')]:
    ...:         print(ele.split(','))
    ...:
['28', '85']
['110', '80']
['118', '80']
['127', '80']
['135', '80']
['141', '80']
['147', '80']
['152', '80']
['156', '80']
['160', '80']
['162', '80']
['164', '80']
['165', '80']
['165', '80']

In [19]: