Chelsea Lewis
Chelsea Lewis

Reputation: 257

How to remove unwanted '\n' from output

file_4 = open('numbers.txt','r')
number_lines = 0
lines = file_4.readlines()[1:]
for file_4 in lines:
    number_lines += 1
print(lines)
print(number_lines)

output: ['2\n', '3\n', '4\n', '5']
         4

My text file has 5 lines

1
2
3
4
5

I want the output to skip the first line, and display the rest. How can I get rid of the /n and also how can I print each of these numbers on a different row instead of on one?

Upvotes: 1

Views: 1162

Answers (5)

Sky
Sky

Reputation: 36

open the file. f.readlines() returns each line in the text file in a list.

Since a list is indexed from 0. list[1:] will skip the first one and give the rest.

with open("stack.txt") as f:
    txt_list = f.readlines() #That's a list
    for item in txt_list[1:]: #skip the first one
        print(item)

output:

2

3

4

5

>>> 

And the \n is nothing but a special character denoting a new line. From your input you read multiple lines each having a new line character at the end. Also print prints each one in a new line. That's the reason for (Two newlines) gap between two numbers in above output.

You can join the list and print like this. Since each already has a new line character in it. What you are doing is printing the entire list in your code. yours:

output: ['2\n', '3\n', '4\n', '5']

Try this:

with open("stack.txt") as f:
    txt_list = f.readlines()
    out = ''.join(txt_list[1:])
print(out)

output:

2
3
4
5

Upvotes: 1

nandal
nandal

Reputation: 2634

Use the following code:-

file_4 = open('numbers.txt','r')
number_lines = 0
lines = file_4.readlines()[1:]
# here we used map() to apply strip() function on each list item to remove \n
lines = map(str.strip, lines)
for file_4 in lines:
    number_lines += 1
# here we use join() with \n to print list item with new line.
print('\n'.join(lines))
print(number_lines)

output:-

2
3
4
5
4

Upvotes: 0

chepner
chepner

Reputation: 532268

A file is an iterator, which means you can use things like next and enumerate directly on the file, instead of reading the entire thing into memory at once. Use strip to remove the trailing newline. (strip actually removes all leading and trailing whitespace; line.lstrip('\n') would remove specifically trailing newlines.)

with open('numbers.txt', 'r') as file_4:
    next(file)  # skip the first line
    for count, line in enumerate(file_4, start=1):
        print(line.strip())
    print("Length:", count)

enumerate basically numbers the lines (here, starting at 1), with count being the current line number. After this loop exits, count is still the number of the last line, which is also the total number of lines.

Upvotes: 0

The simplest fix may be to just change the for-loop variable:

file_4 = open('numbers.txt','r')
number_lines = 0
lines = file_4.readlines()[1:]
for line in lines:       # do not reuse previous variable here 
    number_lines += 1
    print(line.rstrip()) # strip the newline
print(number_lines)

seems to give your expected output:

2
3
4
5
4

Upvotes: 1

jedwards
jedwards

Reputation: 30250

Using .read().splitlines():

file_4 = open('numbers.txt','r')
lines = file_4.read().splitlines()[1:]      # .read().splitlines() will trim the newline chars
number_lines = len(lines)                   # We don't need a loop to count the number of lines
                                            #   We can use the `len` function.
print(lines)                                
print(number_lines)

But this leaves file_4 open, and you're reading the entire file into memory unnecessarily.

Here, using a context manager, looping over the file's lines, and using .rstrip() to trim the newline characters:

with open('numbers.txt','r') as file_4:
    lines = [line.rstrip() for (i,line) in enumerate(file_4) if i > 0]

number_lines = len(lines)
print(lines)                                
print(number_lines)

Upvotes: 0

Related Questions