Home > Mobile >  How to get the first number in each line of a file in python?
How to get the first number in each line of a file in python?

Time:11-30

inputFile = open(filename, "r")

with open(filename) as f:
    content = f.readlines()
li = [x.strip() for x in content]
print(li)

Output:

['4', '0 1 2 3', '1 0 2 3', '2 0 1 3', '3 0 1 2']

Expected Output:

The number of total vertices is 4
Vertex 0: (0, 1) (0, 2) (0, 3)
Vertex 1: (1, 0) (1, 2) (1, 3)
Vertex 2: (2, 0) (2, 1) (2, 3)
Vertex 3: (3, 0) (3, 1) (3, 2) 

I know how to convert a element into an integer but each line is different and the txt file is in this format:

4
0 1 2 3
1 0 2 3
2 0 1 3
3 0 1 2

should I need to separated by.split() method?

CodePudding user response:

Try:

with open("your_file.txt", "r") as f:
    total_vertices = int(next(f))

    vertices = []
    for _ in range(total_vertices):
        row = list(map(int, next(f).split()))
        vertices.append([(row[0], v) for v in row[1:]])

print("The number of total vertices is", total_vertices)
for i, v in enumerate(vertices):
    print(f"Vertex {i}:", *v)

Prints:

The number of total vertices is 4
Vertex 0: (0, 1) (0, 2) (0, 3)
Vertex 1: (1, 0) (1, 2) (1, 3)
Vertex 2: (2, 0) (2, 1) (2, 3)
Vertex 3: (3, 0) (3, 1) (3, 2)
  • Related