Python read from file – newline

Question:

I am writing a list (simple[]) to a file using writelines() and I need each item from the list to be on a new line in the file. I am using the following code:

file_path_simple = r'[path_redacted]tx_list_simple.txt'
    with open(file_path_simple, 'w') as fp:
        for i in simple:
            #ignores any blank lines
            if i == '':
                continue
            else:
                fp.writelines([i])
                fp.writelines('n')
        fp.close()

The problem I am having is that when read from the file later it includes the n, so instead of python reading:

blablabla

it reads:

blablablan

How can I make it not read the n? Or do I need to use something like re.split() to remove the n prior to reading?

This seems like something really simple I am overlooking.

Asked By: user2334659

||

Answers:

You can use rstrip.

i = i.rstrip('n')
Answered By: Unmitigated

The issue is with the way you are using the writelines function. writelines takes a list of strings as input, and writes them to the file. It does not automatically insert newline characters between the strings in the list.

To insert a newline character between each string in your list, you can simply join the strings in the list with a newline character, like this:

with open(file_path_simple, 'w') as fp:
    fp.writelines('n'.join(simple))

This will write each string in the simple list to a new line in the file. When you read the file later, the newline characters will be included in the strings that you read, but that should not cause any issues when you process the strings.

If you do want to remove the newline characters from the strings when you read them later, you can use the strip method to remove leading and trailing whitespace, including newline characters, from the strings.

For example:

with open(file_path_simple, 'r') as fp:
    lines = fp.readlines()

lines = [line.strip() for line in lines]
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.