Reputation: 165
I want to read .txt file and add space after a specific position/index for each line. please consider below example for more details.
suppose my file contains
12345 678 91011 12 1314
In the above file, the first row contains space after a specific position/index [4] , then after position/index[8], after position/index[14] and after position/index[17]
Expected output : I want every row in the file is having space after a specific position. i.e for the first row, I want to add space after index [2], then add space after index [6], then add space after index[11], then add space after index [21], and so on...
123 45 6 78 91 011 12 131 4
As a reminder, I don't want to replace elements but add a new space after a specific position/index.
add space after a specific position/index for each line a text file
suppose my file contains :
12345 678 91 011 12 1314
Expected output :
123 45 6 78 91 011 12 131 4
Upvotes: 0
Views: 1817
Reputation: 1942
Try this. Please note that this is the column position/index we are concerned with. This program adds a space between indexes 2 and 3 like you said. You can add the other indexes as you wish:
with open("C:/path-to-file/file.txt", "r") as file:
lines = file.read().split("\n")
newlines = []
for line in lines:
line = line.rstrip()
newline = line[:3] + ' ' + line[3:] # Add more indexes here
newlines.append(newline)
with open("C:/path-to-file/file.txt", "w") as newfile:
newfile.write("\n".join(newlines))
Upvotes: 1