Я python newb ie, я хочу импортировать значения и параметры из текстового файла и передать его в мою функцию. Как это сделать? - PullRequest
2 голосов
/ 28 января 2020

Я читаю ресурсы в сети. Я узнал, что должен использовать 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

Как мне это сделать?

Ответы [ 3 ]

1 голос
/ 28 января 2020

Вы можете сделать это как,

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]:
0 голосов
/ 28 января 2020

Попробуйте:

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')
0 голосов
/ 28 января 2020

Вот как вы можете это сделать

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
...