This question already has an answer here:
- Reading a file without newlines 8 answers
I have a .txt file with values in it.
The values are listed like so:
Value1
Value2
Value3
Value4
My goal is to put the values in a list. When I do so, the list looks like this:
['Value1\n', 'Value2\n', ...]
The \n
is not needed.
Here is my code:
t = open('filename.txt', 'r+w')
contents = t.readline()
alist = []
for i in contents:
alist.append(i)
This should do what you want (file contents in a list, by line, without \n)
Nota Bene:
rstrip()
removes the whitespaces, that is to say :\f
,\n
,\r
,\t
,\v
,\x
and blank,
but I suppose you're only interested to keep the significant characters in the lines. Then, mere
map(strip, f)
will fit better, removing the heading whitespaces too.If you really want to eliminate only the NL
\n
and RF\r
symbols, do:splitlines() without argument passed doesn't keep the NL and RF symbols (Windows records the files with NLRF at the end of lines, at least on my machine) but keeps the other whitespaces, notably the blanks and tabs.
.
has the same effect as
that is to say the NL and RF are kept
I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.
Sample Code:
After opening the file, list comprehension can do this in one line:
Just remember to close your file afterwards.
for each string in your list, use
.strip()
which removes whitespace from the beginning or end of the string:But depending on your use case, you might be better off using something like
numpy.loadtxt
or evennumpy.genfromtxt
if you need a nice array of the data you're reading from the file.