Home > database >  Python how to remove the trailing new_line character when writting in a file
Python how to remove the trailing new_line character when writting in a file

Time:11-20

So I have a string that I want to write in a file. I am 100% sure that the string has no trailing /n or newline or anything like that. But still, when I try to write it into a file it adds a new line to the file at the, and I do not understand why. I need to have the last line of the file without the automatically added '/n'. Do you know how can I do this?

sample of written file: enter image description here

The writing code (the matrix always has 9 rows and 9 columns):

    output = ""
    index = 0
    for each_line in structure_matrix:
        for each_tile in each_line:
            output  = str(each_tile)
        index  = 1
        if index % 3 == 0 and index != 9:
            output  = "\n"
            index = 0
    file_to_write_in_predictions.write(output)

Thanks!

CodePudding user response:

So what I would do. I would create a new list composed of the lines you created while using your data and then inside "with" statement I would create a logic that writes each item from the list to a txt file and unless its the last one it adds a new line to it. I tested it for the following data and it seems to work

some_data_c = [1, 2, 3, 4, 5, 6, 7, 8, 9]
some_data_r = [1, 2, 3, 4, 5, 6, 7, 8, 9]
output = ""
new_row = []
for c in some_data_c:
    for r in some_data_r:
        output  = str(r)    
    new_row.append(output)
    output = ""
print(new_row)
with open("test.txt", "w") as f:
    for i in range(len(new_row)):
        print(i)
        if i < (len(new_row)-1):
            f.write(new_row[i] "\n")
        else:
            f.write(new_row[i])

CodePudding user response:

Because you reset index to 0 every time it is a multiple of 3, it will never reach 9 and the condition if index % 3 == 0 and index != 9 will be true for the 9th line as well. Removing index = 0 should do the trick.

  • Related