Stephen Boyette
Stephen Boyette

Reputation: 31

Add text to the end of a file in Python, but without creating a new line

I am attempting to update a series of .csv files to add a missing column delimiter. However, my attempt at appending this character is generating a line break after the delimiter. I see that 'append' is designed exactly for that purpose - to append a new line to a file. Where should I be looking to accomplish this desired output:

Input:
Header|
Data

Output:
Header|
Data|

For reference I've checked several such SO questions as: How do you append to a file in Python?

Code for reference:

import os

with open("myNewFile.txt", "a+") as myfile:
    myfile.write("|")

For further reference, currently my result looks like:

Header|
Data
| (with the pipe character added on a new line)

Upvotes: 0

Views: 1959

Answers (3)

Sebcworks
Sebcworks

Reputation: 139

The problem is that your file ends with a newline, you will have to start a new one.

lines = []
with open("myNewFile.txt", "r") as myfile:
    lines = myfile.readlines()
lines[-1] = lines[-1].strip()+"|"
with open("copy.txt", "w") as outfile:
    for line in lines:
        outfile.write(line)

Should work as you want.

Upvotes: 0

manu190466
manu190466

Reputation: 1603

As suggested by @jordanm you probably have a trailing newline in your file. To remove it you have to read the file first to get its contents in a string.

with open("myOldFile.txt", "r") as myfile:
    filestring=myfile.read()

Then remove the trailing newline :

filestring=filestring.rstrip()

Finaly write the new file :

with open("myNewFile.txt", "a+") as myfile:
    myfile.write(filestring+"|")

Upvotes: 2

georgekrax
georgekrax

Reputation: 1189

If I understand your question correctly, you should do something like this:

print("Hello" , end = ' ')  
print("world!")

By this way, the code will print:

Hello world!

For your issue, you have also to write context inside of a file. That is how you might implement it:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

If you only use \n at the end of the string, on the f.write() method, then only a new line will be printed and then you next write() method will start from a new line.

*Use a for append, and w for overriding the current context and writing again the file form the start.

I hope that helps. Please let me know if it solved your issue.

Upvotes: 0

Related Questions