Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting rid of \n when using .readlines() [duplicate]

People also ask

How do I strip a new line in Readlines?

If you want to strip the newline character \n from each line when adding it to a list you can use the strip() method within a list comprehension: with open('file. txt') as f: lines = [ line.

Does readline () take in the \n at the end of line?

In addition to the for loop, Python provides three methods to read data from the input file. The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end.

How do you get rid of N in a text file in Python?

Use the strip() and the rstrip() Methods to Read a Line Without a Newline in Python. The strip() method in Python helps in omitting the spaces that are present at the beginning (leading) and at the end (trailing). Besides white spaces, the strip() method also includes the newline characters.

What does the Readlines () return?

The readlines() method returns a list containing each line in the file as a list item.


This should do what you want (file contents in a list, by line, without \n)

with open(filename) as f:
    mylist = f.read().splitlines() 

I'd do this:

alist = [line.rstrip() for line in open('filename.txt')]

or:

with open('filename.txt') as f:
    alist = [line.rstrip() for line in f]

You can use .rstrip('\n') to only remove newlines from the end of the string:

for i in contents:
    alist.append(i.rstrip('\n'))

This leaves all other whitespace intact. If you don't care about whitespace at the start and end of your lines, then the big heavy hammer is called .strip().

However, since you are reading from a file and are pulling everything into memory anyway, better to use the str.splitlines() method; this splits one string on line separators and returns a list of lines without those separators; use this on the file.read() result and don't use file.readlines() at all:

alist = t.read().splitlines()

After opening the file, list comprehension can do this in one line:

fh=open('filename')
newlist = [line.rstrip() for line in fh.readlines()]
fh.close()

Just remember to close your file afterwards.


I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.

Sample Code:

with open('C:\\aapl.csv','r') as apple:
    for apps in apple.readlines():
        print(apps.strip())