Problem
I have a.txt file that contains values.
The following is a list of the values:
Value1
Value2
Value3
Value4
My goal is to make a list of the values. When I do so, the following appears on the list:
[‘Value1\n’, ‘Value2\n’, …]
The n isn’t required.
My code is as follows:
t = open('filename.txt', 'r+w')
contents = t.readline()
alist = []
for i in contents:
alist.append(i)
Asked by TDNS
Solution #1
This should fulfill your requirements (file contents in a list, by line, without \n)
with open(filename) as f:
mylist = f.read().splitlines()
Answered by user3131651
Solution #2
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]
Answered by hughdbrown
Solution #3
To remove only newlines from the end of a string, use.rstrip(‘n’):
for i in contents:
alist.append(i.rstrip('\n'))
All other whitespace is unaffected. The huge heavy hammer is called if you don’t care about whitespace at the beginning and end of your lines. strip().
However, since you’re reading from a file and will be storing everything in memory, you should use the str.splitlines() method, which splits a string along line separators and gives a list of lines without those separators; apply this on the file. Instead of using file.readlines(), read() the result:
alist = t.read().splitlines()
Answered by Martijn Pieters
Solution #4
List comprehension may perform this in one line after opening the file:
fh=open('filename')
newlist = [line.rstrip() for line in fh.readlines()]
fh.close()
Just remember to save your work when you’re done.
Answered by Lisle
Solution #5
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())
Answered by Yogamurthy
Post is based on https://stackoverflow.com/questions/15233340/getting-rid-of-n-when-using-readlines