how to add a new line in a text file using python without \n

python, python-3.x

Solution

Your question doesn't actually make sense, because of what a "line" actually is and what that `'\n'` character means.

Files don't have an intrinsic concept of lines. A file is just a sequence of bytes. `'\n'` is the line separator (as Python represents it with universal newlines). If you want your data to show up on different "lines", you must put a line separator between them. That's all that the `'\n'` character is. If you open up the file in a text editor after you write it, most editors won't explicitly show the newline character by default, because it's already represented by the separation of the lines.

To break down what your code is doing, let's look at the `add` method, and fix some things along the way.

The first thing `add` does is name a variable called `nl` and assign it the newline character. From this, I can surmise that `nl` stands for "newline", but it would be much better if that was actually the variable name.

Next, we name a variable called `acc` and assign it the `'.acc'` suffix, presumably to be used as a file extension or something.

Next, we make a variable called `xy` and assign it to `x + acc`. `xy` is now a string, though I have no idea of what it contains from the variable name. With some knowledge of what `x` is supposed to be or what these lines represent, perhaps I could rename `xy` to something more meaningful.

The next three lines create three new variables called `exyz`, `xyz`, and `xxx`, and point them all to the same string that `xy` references. There is no reason for any of these lines whatsoever, since their values aren't really used in a meaningful way.

Now, we open a file. Fine. Maybe `tf` stands for "the file"? "text file"? Again, renaming would make the code much more friendly.

Now, we call `tf.writelines(nl)`. This writes the newline character (`'\n'`) to the file. Since the `writelines` method is intended for writing a whole list of strings, not just a single character, it'll be cleaner if we change this call to `tf.write(nl)`. I'd also change this to write the newline at the end, rather than the beginning, so the first time you write to the file it doesn't insert an empty line at the front.

Next, we call `writelines` again, with our data variable (`xxx`, but hopefully this has been renamed!). What this actually does is break the iterable `xxx` (a string) into its component characters, and then write each of those to the file. Better replace this with `tf.write(xxx)` as well.

Finally, we have `tf.close`, which is a reference to the `close` function of the file object. It's a no-op, because what you presumably meant was to close the file, by calling the method: `tf.close()`. We could also wrap the file up as a context manager, to make its use a little cleaner. Also, most of the variables aren't necessary: we can use string formatting to do most of the work in one step. All in all, your method could look like this at the end of the day:

def add(x):
    with open('accounts.dat',"a+") as output_file:
        output_file.write('{0}.acc\n'.format(x))

So you can see, the reason the `'\n'` appears at the end of every line is because you are writing it between each line. Furthermore, this is exactly what you have to do if you want the lines to appear as "lines" in a text editor. Without the newline character, everything would appear all smashed together (take out the `'\n'` in my `add` method above and see for yourself!).

The problem you described in the comment is happening because `names` is a direct reading of the file. Looking at the `readlines` documentation, it returns a list of the lines in the file, breaking at each newline. So to clean those names up, you want line 4 of the code you posted to call `str.strip` on the individual lines. You can do that like this:

names = tf.readlines()
for i in range(len(names)):
    names[i] = names[i].strip() # remove all the outside whitespace, including \n

However, it's much cleaner, quicker, and generally nicer to take advantage of Python's list comprehensions, and the fact that file objects are already iterable line-by-line. So the expression below is equivalent to the previous one, but it looks far nicer:

names = [line.strip() for line in tf]

Problem

I have a file that has a list of files but it adds `\n` at the end how can I have python just write the info I need on a new line without getting `\n` in the way so that way my info will be called `X.acc` not `x.acc\n`? Here is my code that writes the file ``` def add(x): nl = "\n" acc = ".acc" xy = x + acc exyz = xy xyz = exyz xxx = str(xyz) tf = open('accounts.dat',"a+") tf.writelines(nl) tf.writelines(xxx) tf.close ``` Here is the code that calls upon the file: ``` import sys tf = open('accounts.dat','r') names = tf.readlines() u = choicebox(msg="pick something",title = "Choose an account",choices=(names)) counter_file = open(u, 'r+') content_lines = [] for line in counter_file: if line == "credits =": creds = line else: False for line in counter_file: if 'credits =' in line: line_components = line.split('=') int_value = int(line_components[1]) + 1 line_components[1] = str(int_value) updated_line= "=".join(line_components) content_lines.append(updated_line) else: msgbox(msg=(creds)) content_lines.append(line) counter_file.seek(0) counter_file.truncate() counter_file.writelines(content_lines) counter_file.close() ``` thank you for your help and sorry if this is a trival question still new to python :)

Original source