To Read Line from File Without Getting "\N" Appended at the End

How to read a file without newlines?

You can read the whole file and split lines using str.splitlines:

temp = file.read().splitlines()

Or you can strip the newline by hand:

temp = [line[:-1] for line in file]

Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.

This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).

If you want to avoid this you can add a newline at the end of file:

with open(the_file, 'r+') as f:
f.seek(-1, 2) # go at the end of the file
if f.read(1) != '\n':
# add missing newline if not already present
f.write('\n')
f.flush()
f.seek(0)
lines = [line[:-1] for line in f]

Or a simpler alternative is to strip the newline instead:

[line.rstrip('\n') for line in file]

Or even, although pretty unreadable:

[line[:-(line[-1] == '\n') or len(line)+1] for line in file]

Which exploits the fact that the return value of or isn't a boolean, but the object that was evaluated true or false.


The readlines method is actually equivalent to:

def readlines(self):
lines = []
for line in iter(self.readline, ''):
lines.append(line)
return lines

# or equivalently

def readlines(self):
lines = []
while True:
line = self.readline()
if not line:
break
lines.append(line)
return lines

Since readline() keeps the newline also readlines() keeps it.

Note: for symmetry to readlines() the writelines() method does not add ending newlines, so f2.writelines(f.readlines()) produces an exact copy of f in f2.

to read line from file without getting \n appended at the end

To remove just the newline at the end:

line = line.rstrip('\n')

The reason readline keeps the newline character is so you can distinguish between an empty line (has the newline) and the end of the file (empty string).

Ignoring \n when reading from a file in C?

C doesn't provide much in the way of conveniences, you have to provide them all yourself or use a 3rd party library such as GLib. If you're new to C, get used to it. You're working very close to the bare metal silicon.

Generally you read a file line by line with fgets(), or my preference POSIX getline(), and strip the final newline off yourself by looking at the last index and replacing it with a null if it's a newline.

#include <string.h>
#include <stdio.h>

char *line = NULL;
size_t line_capacity = 0; /* getline() will allocate line memory */

while( getline( &line, &line_capacity, fp ) > 0 ) {
size_t last_idx = strlen(line) - 1;

if( line[last_idx] == '\n' ) {
line[last_idx] = '\0';
}

/* No double newline */
puts(line);
}

You can put this into a little function for convenience. In many languages it's referred to as chomp.

#include <stdbool.h>
#include <string.h>

bool chomp( char *str ) {
size_t len = strlen(str);

/* Empty string */
if( len == 0 ) {
return false;
}

size_t last_idx = len - 1;
if( str[last_idx] == '\n' ) {
srt[last_idx] = '\0';
return true;
}
else {
return false;
}
}

It will be educational for you to implement fgets and getline yourself to understand how reading lines from a file actually works.

Reading lines in a file that end with \n

The caveat here is that except for the literal '\n' there is also an actual \n at the end of each line (except for the last line, which only has the literal '\n'):

with open('test.txt') as f:
print(f.readlines())
# ['3 2\\n\n', '#1###2#\\n\n', '****#**\\n\n', '##*###*\\n\n', '#******\\n\n', '#*#O##*\\n']

You need to call .strip with both the literal '\n' and the actual \n:

with open('test.txt') as f:
lines = [line.strip('\\n\n') for line in f]

print(lines)
# ['3 2', '#1###2#', '****#**', '##*###*', '#******', '#*#O##*']

What's wrong with my code to read and replace python text file line by line?

There's no such thing as "replacing an existing line" in a file. For what you want to do, you have to write a new file with the modified content and then replace the old file with the new one. Example code:

with open("old.file") as old, open("new.file", "w") as new:
for line in old:
line = modify(line.lstrip())
new.write(line + "\n")
os.rename("new.file", "old.file")

Append lines from a text file to a list in python without '\n'

readlines() puts a newline at the end of every text line. You can use rstrip() to remove it:

f = open('./users/login.txt', 'r+')
f1 = f.readlines()
for ele in f1:
users.append(ele.rstrip())

\n' is getting added at the end of each line in a dictionary

Use line.strip() for your {'fileLine': line.strip()}



Related Topics



Leave a reply



Submit