Connecting Tech Pros Worldwide Help | Site Map

Problem: Python printing one line on two lines!

Newbie
 
Join Date: Jul 2009
Posts: 14
#1: Aug 22 '09
Expand|Select|Wrap|Line Numbers
  1. l__trace = "<my path\file_with_two_lines.txt>
  2.  
  3. if __name__=='__main__':
  4.  
  5.     l__open = open(l__trace,'r')
  6.     for l__line in l__open.readlines():
  7.         (head,tail) = os.path.split(l__line)
  8.         if head:
  9.             print head + "\\" + tail  + "_new"      # <----Problem
The script opens a file with TWO LINES:
-> this\is\the\first\line <----these are actually directories
-> this\is\the\second\line <----these are actually directories

I want this: (when i print)
this\is\the\first\line_new
this\is\the\second\line_new

Instead I get this:
this\is\the\first\line
_new
this\is\the\second\line_new

Notice that the second line is ok because there isn't a third line, first line is not ok beacuse of the second line, how can i print the "_new" on the same line (first line) like with line two? if i add a third line, line two does the same? this is a BUG in python.
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,561
#2: Aug 23 '09

re: Problem: Python printing one line on two lines!


Nope, no bug here. You need to strip the newline character!

Expand|Select|Wrap|Line Numbers
  1.         head,tail = os.path.split(l__line.strip())
Newbie
 
Join Date: Jul 2009
Posts: 14
#3: Sep 11 '09

re: Problem: Python printing one line on two lines!


I used re.sub("\n","",my_line). Thanks anyway for the reply.
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,561
#4: Sep 11 '09

re: Problem: Python printing one line on two lines!


Of course that works, but I much prefer to use string methods where possible over re.
Newbie
 
Join Date: Sep 2009
Posts: 1
#5: Sep 25 '09

re: Problem: Python printing one line on two lines!


Quote:

Originally Posted by bvdet View Post

Of course that works, but I much prefer to use string methods where possible over re.

strings module present rstrip and lstrip structures.
Use (head,tail) = os.path.split(l__line.rstrip('\n'))
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,561
#6: Sep 25 '09

re: Problem: Python printing one line on two lines!


Quote:

Originally Posted by Diablus View Post

strings module present rstrip and lstrip structures.
Use (head,tail) = os.path.split(l__line.rstrip('\n'))

In your example, rstrip() and lstrip() are string methods. The string module defines rstrip() and lstrip() as functions. These functions are deprecated, but remain in Python versions prior to 3.0.
Reply