0

I'm very new to python so I have no idea how to even start this.

I have several TFS files and I need to read them and create a new file with a specific row and column from the other files.

Ex:

file 1:

x 1 # A
y 2 % B
z 3 * C

file 2:

x1 4 # A
y1 5 % B
z1 6 * C

file 3:

x2 7 # A
y2 8 % B
z2 9 * C

Expected output file:

y 2 B
y1 5 B
y2 8 B 

(row 1 and columns 0, 1, 3 from all files)

zvezdy
  • 9
  • 1
  • 1
    break the problem down into steps and work out how to do each step. you need to: open a file, read a specific line from the file (then you can google how to do that e.g. https://stackoverflow.com/questions/2081836/how-to-read-specific-lines-from-a-file-by-line-number) then when you have the line you want you need to split it into columns (https://stackoverflow.com/questions/3475251/split-a-string-by-a-delimiter-in-python) and get just the column values you want, then write those values to the output file (https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file) – Anentropic Jun 07 '22 at 13:35

1 Answers1

0

Here is how you can use the built-in enumerate() method:

result = []
row = 1
cols = [0, 1, 3]

files = ["file1.tfs", "file2.tfs", "file3.tfs"]

for file in files:
    with open(file) as f:
        for i, line in enumerate(f):
            if i == row:
                result.append(" ".join(char for j, char in enumerate(line.split()) if j in cols))
                break

print("\n".join(result))

Output:

y 2 B
y1 5 B
y2 8 B

For convenience in testing out this code, I replaced the files with lists of strings here:

result = []
row = 1
cols = [0, 1, 3]

fs = [
    ["x 1 # A", "y 2 % B", "z 3 * C"],
    ["x1 4 # A", "y1 5 % B", "z1 6 * C"],
    ["x2 7 # A", "y2 8 % B", "z2 9 * C"]
]

for f in fs:
    for i, line in enumerate(f):
        if i == row:
            result.append(" ".join(char for j, char in enumerate(line.split()) if j in cols))
            break

print("\n".join(result))

Output:

y 2 B
y1 5 B
y2 8 B
Red
  • 26,798
  • 7
  • 36
  • 58