Hello. I try to manipulate files with content type text. Im getting an error which Im not able to correct. Perhaps someone here could help to correct the error?
I have several text files, each containing 6 lines, in a directory:
1.0000000000
0.0000000000
0.0000000000
-1.0000000000
200425.5000000000
6546004.5000000000
I try to achieve this for each file
200425.5000000000 6546004.5000000000
(4 first lines deleted and moved position (East and North) to line 1
Attached is the code and errormessage.
Thank You
import os
# map containing the heightfiles
directory = 'k:/kartverket/DTM1_12-10_UTM33_20230929'
# for each file in the map
for filename in os.listdir(directory):
if filename.endswith('.tfw'): # check that file is a textfile
with open(os.path.join(directory, filename), 'r') as file:
lines = file.readlines()
# delete 4 first lines
del lines[0:4]
# move text in line 6 beside the word in line 5 seperated by a space
lines[4] = lines[4].strip() + ' ' + lines[5]
# delete line 6
del lines[5]
# move ttext in line 5 to line1
lines.insert(0, lines.pop(4))
# write changes back to file
with open(os.path.join(directory, filename), 'w') as file:
file.writelines(lines)
ERRORMSG::
[Running] python -u “d:\kartprojects\mantext.py”
Traceback (most recent call last):
File “d:\kartprojects\mantext.py”, line 15, in
lines[4] = lines[4].strip() + ’ ’ + lines[5]
~~~~~^^^
IndexError: list index out of range
to delete the first four lines, read the last two, and write the data from the last two lines in a serial manner, we can accomplish this by the following code snippet (you will have to edit the file path to suit your own file name and directory). Note that I have commented the script detailing the majority of the lines for reference.
from pathlib import Path
FILE_PATH = Path('/Users/myComp/Desktop/raw_data_six_lines.txt')
def read_data(filename):
with open(filename) as file: # Open the file to read
data = file.readlines() # Read the file contents
num_data = [] # Data appended to a list
for index, line in enumerate(data): # iterate through each line
if index >= 4 and index <= 5: # Only append line 5 and line 6 data
num_data.append(line.replace('\n', '')) # Remove the newline character from each
# line
write_back = str(num_data[0]) + ' ' + str(num_data[1]) # Create one string from the two values
# and add a space in between
open(filename).close() # This erases the file contents
with open(filename, 'w') as file: # Open the file again to write to
file.write(write_back) # Write the data back to the original file
read_data(FILE_PATH)
Think carefully about the logic. After you have donedel lines[0:4], how many lines do you expect should remain in the lines? What indices do you think they would have?
Instead of trying to manipulate the lines list, it will be much simpler to think in terms of creating new data. If you have all 6 lines, what rule would you use to create the single, new line that you want? (Would it be useful to put this line into a list? Why or why not?)