Next line escape character not working python - python

I used the following code to read from a text file line by line and print it on screen.
with open("source.txt") as f:
content = f.readlines()
print(content)
print('\n')
f.close()
But the \n was just getting appended to the output and the output was coming in a single line instead. For example if the file was like this:
abc
def
ghi
the output was:
['abc\n', 'def\n', 'ghi']
Then I tried changing the single quotes with the '\n' with "\n" like this:
with open("source.txt") as f:
content = f.readlines()
print(content)
print("\n")
f.close()
The actual output I need is:
abc
def
ghi
What can i do for that? Operating platform: Mac(Unix) Thanks in advance.

You should do it this way:
with open('source.txt', 'r') as f:
for line in f: #iterate over lines
line = line.strip() #removes whitespaces and new lines
print line #print the line, the print function adds new line
readlines() loads the whole file in memory and if the file is bigger than your memory you can't read it, so iterate over the file.

You can use rstrip():
>>> for i in content:
... print i.rstrip()
...
abc
def
ghi
The problem with your code is that it isn't doing what you would expect it to do. content is a list, and printing the list would just have ['abc\n', etc]. You can use a for-loop (as I have shown) to go through each element in the list and individually print out all the elements on a separate line.
I'm not exactly sure why you have print('\n'), but I'm presuming that you come from another programming language. Python automatically adds a newline, so adding one is not needed :).
Finally, rstrip() is needed to strip the newline, otherwise this would appear:
>>> for i in L:
... print i
...
abc
def
ghi

The problem is you were trying to print the list object itself, instead you should loop over the list and print individual items:
>>> lis = ['abc\n', 'def\n', 'ghi']
>>> print lis
['abc\n', 'def\n', 'ghi']
print lis actually prints the str representation of the list object:
>>> print str(lis)
['abc\n', 'def\n', 'ghi']
Loop over the list and print individual items. In python we can loop over the list itself unlike C/C++ where we require indexes.
>>> for item in lis:
... print item.rstrip('\n') #removes the trailing '\n'
...
abc
def
ghi
A for-loop over a list or any other iterable returns the next item from that iterable one by one and assigns it to the variable used in for-loop:
for x in lis: #in each iteration x is assgined the next item from lis
print x

with open('source.txt', 'r') as f:
content = f.read()
print content

Related

Output using readlines in Python

I was wondering if anyone had an answer for this. In the image the top case has the code,
output of the two different lines of code from below:
def stats ():
inFile = open('textFile.txt', 'r')
line = inFile.readlines()
print(line[0])
and the second case has the code,
def stats ():
inFile = open('textFile.txt', 'r')
line = inFile.readlines()
print(line[0:1])
instead of going to the next iteration and printing it, it just spits out the iteration, now populated with all the \t and the end of line character \n. Can anyone explain why this is happening?
In the first case you're printing a single line, which is a string.
In the second case you're printing a slice of a list, which is also a list. The strings contained within the list use repr instead of str when printed, which changes the representation. You should loop through the list and print each string separately to fix this.
>>> s='a\tstring\n'
>>> print(str(s))
a string
>>> print(repr(s))
'a\tstring\n'
>>> print(s)
a string
>>> print([s])
['a\tstring\n']

How to get a list from a file in python

I am trying to get the contents of a file in a list. For reference: these are the contents of the file:
1. item1
2. item2
3. item3
I am able to open the files, and when I do file.read(), all I get from the interpreter is an empty string:
>>> file = open("C:\\Users\\vivrd\\Desktop\\testing.txt")
>>> file.read()
''
If I do file.readlines(), it displays a list, but even though the python docs say that file.readlines() returns a list, whenever I try to assign a variable to it (to access the list), all I get is an empty list:
>>> file.readlines()
['1. item1\n', '2. item2\n', '3. item3'] #returns the list
>>> item = file.readlines()
>>> item #but the list is empty!
[]
I have also tried to loop through the file, but it doesn't print out anything:
>>> for line in file:
print(line)
>>>
Also, for some reason, file.readlines() is only working once. I tried it a second time, and the interpreter didn't even display anything:
>>> file.readlines()
[]
My target is to get a list that looks like this: ["1. item1", "2. item2", "3. item3"] or even with the escape sequences (though not preferable): ["1. item1 \n", "2. item2 \n", "3. item3"]
How can I get to this point? Thanks!
It will work only once, because after that, python is done reading the file (here's a question that discusses this in detail). Read it once and store it in a variable:
>>> f = open("C:\\Users\\vivrd\\Desktop\\testing.txt")
>>> items = f.readlines() # items should now be a list of lines in the file
>>> f.close() # make sure to close the file
If you want to re-read, move the 'cursor' back to the beginning of the file (before closing) using seek:
>>> items = f.readlines()
>>> f.seek(0)
>>> more_items = f.readlines()
>>> f.close()
Try with these lines of codes .
with open(filename , "r") as file:
content=file.readlines()
for lines in content:
print(lines)

Programmatically create a list of lists in Python 2.7

I'm trying to create a list of lists by reading a file of data and I can't get it to work.
To show what I'm trying to do I have the following hard-coded list of lists that works for my purpose. Each list contains a room name, followed by an x and y coordinate. This is for a robot navigation program.
Here's the hard-coded listing that works.
nav_Array =[["studio",145.0,155.0],["kitchen",245.0,400.0]]
print (nav_Array[0])
print (nav_Array[1])
print ("\n")
print (nav_Array[0][0])
print (nav_Array[0][1])
print (nav_Array[0][2])
print ("\n")
print (nav_Array[1][0])
print (nav_Array[1][1])
print (nav_Array[1][2])
Here's the printed output I expected and got:
['studio', 145.0, 155.0]
['kitchen', 245.0, 400.0]
studio
145.0
155.0
kitchen
245.0
400.0
Now for my problem.
I have the following text file: I can modify the format of this file if need be, but I'd like to keep each entry on a new line for ease of maintenance. This is a very short excerpt of this file. The actual file is going to have many more lists. Each line being a list. By the way I've tried adding brackets and that doesn't help as you'll see further down:
studio,145.0,155.5
kitchen,245.0,400.0
So the problem is that I want to read this file into a list of lists like I had manually typed in as nav_Array in the previous example.
Here's what I tried.
First Attempt:
with open(file_path) as myfile:
for line in myfile:
line = line.rstrip()
print (line)
nav_Array.append(line)
myfile.close()
print "\n"
print "print nav_Array: ", nav_Array
print "\n"
print (nav_Array[0][0])
print (nav_Array[0][1])
print (nav_Array[0][2])
print "\n"
print (nav_Array[1][0])
print (nav_Array[1][1])
print (nav_Array[1][2])
The result is the following which is not what I want:
studio,145.0,155.5
kitchen,245.0,400.0
print nav_Array: ['studio,145.0,155.5', 'kitchen,245.0,400.0']
s
t
u
k
i
t
That's not creating a list of lists.
So then I tried adding brackets to the original file data like so:
[studio,145.0,155.5]
[kitchen,245.0,400.0]
Then running the same program as above I get the following output which is better, but still not a list of lists. The following is the output:
[studio,145.0,155.5]
[kitchen,245.0,400.0]
print nav_Array: ['[studio,145.0,155.5]', '[kitchen,245.0,400.0]']
[
s
t
[
k
i
For some reason single quotes are being put in by the append function. And that ruins what I'm trying to do. If I could get rid of those single quotes I'd be home free.
So then I tried the following to the original file format. All I did here was trying to add the [] in the append function itself, but this gives me precisely the same result as placing the [] in the data file.
The only line difference here is nav_Array.append("["+line+"]")
with open(file_path) as myfile:
for line in myfile:
line = line.rstrip()
print (line)
nav_Array.append("["+line+"]")
myfile.close()
print "\n"
print "print nav_Array: ", nav_Array
print "\n"
print (nav_Array[0][0])
print (nav_Array[0][1])
print (nav_Array[0][2])
print "\n"
print (nav_Array[1][0])
print (nav_Array[1][1])
print (nav_Array[1][2])
And this gives me the same output I got when I added the square brackets to the data file directly.
studio,145.0,155.5
kitchen,245.0,400.0
print nav_Array: ['[studio,145.0,155.5]', '[kitchen,245.0,400.0]']
[
s
t
[
k
i
Again that's not what I need. I need what I got when I typed in the list of lists by hand in the first example at the top of this post.
Just for the record, I've been trying tons of other things as well. I've been reading a lot of Stack Overflow posts on how to import lists from files, but I haven't been able to find anything that addresses bringing in an actual list of lists.
I'm almost there! I just can't get rid of the single quotes that appear to be introduced automatically by the append function.
I'm thinking I could write a program to go through and strip out those single quotes as a last resort. But surely there's a better way to build a list of lists without having to do that.
Thanks for reading.
Make use of splitlines and split:
s = """
studio,145.0,155.5
kitchen,245.0,400.0
"""
final = [i.split(',') for i in s.splitlines() if i]
print(final)
Output:
[['studio', '145.0', '155.5'], ['kitchen', '245.0', '400.0']]
Or for a file:
test.txt
studio,145.0,155.5
kitchen,245.0,400.0
You can use:
with open('test.txt') as f:
final = [i.split(',') for i in f.read().splitlines() if i]
print(final)
Output:
[['studio', '145.0', '155.5'], ['kitchen', '245.0', '400.0']]
The csv module works well with csv files. :)
import csv
with open('my.csv') as f:
reader = csv.reader(f)
a = list(reader)
print(a)
>>>
[['studio', '145.0', '155.5'], ['kitchen', '245.0', '400.0']]
>>>

Reading inputs written in different lines from a file and storing each input inside a list

I'm trying to read a file named one.txt which contains the following:
hat
cow
Zu6
This is a sentence
and I'm trying to store each string written on each line inside a list. For example, my output list should contain the following elements:
['hat', 'cow', 'Zu6', 'This is a sentence']
Here's my approach for doing this:
def first(ss):
f = open(ss, 'r')
text = f.readline()
f.close()
lines = []
li = [lines.append(line) for line in text]
print li
first('D:\\abc\\1\\one.txt')
However, when I try to print li, here's what I get as the output:
[None, None, None, None]
What's wrong with my approach?
print list(open("my_text.txt"))
is probably a pretty easy way to do it ...
ofc people are gonna come screaming about dangling pointers so for the sake of good habits
with open("my_text.txt") as f:
print list(f)
alternatively
f.readlines()
you might need to strip off some newline characters
[line.strip() for line in f]

python line separated values in a text when converted to list, adds "\n" to the elements in the list

I was astonished that a thing this simple has been troubling me. Below is the code
list = []
f = open("log.txt", "rb") # log.txt file has line separated values,
for i in f.readlines():
for value in i.split(" "):
list.append(value)
print list
The output is
['xx00', '\n', 'xx01in', '\n', 'xx01na', '\n', 'xx01oz', '\n', 'xx01uk', '\n']
How can I get rid of the new line i.e. '\n'?
list = []
f = open("log.txt", "rb") # log.txt file has line separated values,
for i in f.readlines():
for value in i.strip().split(" "):
list.append(value)
print list
.strip() removes trailing newlines. to be explicit you can use .strip('\n') or .strip('\r\n') in some cases.
you can read more about .strip() here
edit
better way to do what you wanted:
with open("log.txt", 'rb') as f:
mylist = [val for subl in [l.split(' ') for l in f.read().splitlines()] for val in subl]
for an answer which is much easier on the eyes, you can import itertools and use chain to flatten the list of lists, like #Jon Clements example
so it would look like this:
from itertools import chain
with open("log.txt", 'rb') as f:
mylist = list(chain.from_iterable(l.split(' ') for l in f.read().splitlines()))
If line-separated means that there is only one value per line, you don't need split() at all:
with open('log.txt', 'rb') as f:
mylist = map(str.strip, f)
In Python 3 wrap map() in a list().
with open("log.txt", "rb") as f:
mylist = f.read().splitlines()
Also, don't use list as a variable name, as it overshadows the python type list().
The correct way to do this, is:
with open('log.txt') as fin:
for line in fin:
print line.split()
By using split() without an argument, the '\n''s automatically don't become a problem (as split or split(None) uses different rules for splitting).
Or, more concisely:
from itertools import chain
with open('log.txt') as fin:
mylist = list(chain.from_iterable(line.split() for line in fin))
If you have a bunch of lines with space separated values, and you just want a list of all the values without caring about where the line breaks were (which appears to be the case from your example, since you're always appending to the same list regardless of what line you're on), then don't bother looping over lines. Just read the whole file as a single string and call split() with no arguments; it will split the string on any sequence of one or more whitespace characters, including both spaces and newlines, with the result that none of the values will contain any whitespace:
with open('log.txt', 'rb') as f:
values = f.read().split()

Categories

Resources