1

I want to modify a folder with .txt files

The txt file look like this:

3 0.695312 0.523958 0.068750 0.052083
3 0.846875 0.757292 0.071875 0.031250
3 0.830469 0.719792 0.067187 0.035417

My idea is take all the .txt files and change inline the first number.

Output example:

2 0.695312 0.523958 0.068750 0.052083
2 0.846875 0.757292 0.071875 0.031250
2 0.830469 0.719792 0.067187 0.035417

Can you help me?

DevLounge
  • 8,313
  • 3
  • 31
  • 44

1 Answers1

2

I think this code should go. Let me know if is what you intend to.

import os

files = []
# Add the path of txt folder
for i in os.listdir("C:\data"):
    if i.endswith('.txt'):
        files.append(i)

for item in files:
    # define an empty list
    file_data = []

    # open file and read the content in a list
    with open(item, 'r') as myfile:
        for line in myfile:
            # remove linebreak which is the last character of the string
            currentLine = line[:-1]
            data = currentLine.split(" ")
            # add item to the list
            file_data.append(data)
    
    # Decrease the first number in any line by one
    for i in file_data:
        if i[0].isdigit():
            temp = float(i[0]) - 1
            i[0] = str(int(temp))

    # Write back to the file
    f = open(item, 'w')
    for i in file_data:
        res = ""
        for j in i:
            res += j + " "
        f.write(res)
        f.write("\n")
    f.close()

This program read a file and decrease all the first number in any line by one. Then it write it back to the file.

Eitan Rosati
  • 543
  • 5
  • 18