0

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)

3 Answers3

1

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+"|")
manu190466
  • 1,557
  • 1
  • 9
  • 17
0

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.

georgekrax
  • 1,065
  • 1
  • 11
  • 22
  • Close! I'm trying to add to the end of a file, rather than print it out. Do I need to be doing the same thing, though, and looking for the 'end' of the file? Do I need to read the original file, add the character to it, and then save a new file? – Stephen Boyette May 07 '20 at 16:53
0

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.

Sebcworks
  • 139
  • 2
  • 7