The readlines() method for file objects return the lines as a list (or is it a tuple?)
however each element contains the \n character which prevents the element from being used in another function. How do I remove the \n character from the elements?

I have made some code which Will make return the two lines after the word "path" in a text file.
The return statement will return the line with the \n character. That's where the problem i mentioned arises

def rec_paths(files):
	f=open(files)
	g=f.readlines()
	
	line=1
	for a in g:
		if 'path' in a:
			#print(g[line],end='')
			#print(g[line+1],end='')
			return(g[line])
			
			line=line+1
		
		else:
			line=line+1
			continue	
		
		
print(rec_paths('C:\\Documents and Settings\\folderX\\Desktop\\t.txt'))

(I can use end=' ' for the print statements but not for the return statements to get rid of the \n)

Recommended Answers

All 14 Replies

line=line.rstrip('\n') #this strips the newline character from the line

commented: good help +11

Do yourself and the rest of us a favor and don't use tabs for indentations.

Do yourself and the rest of us a favor and don't use tabs for indentations.

Not sure what I did wrong, I wasn't aware of using any indentation in my response. Is it because I didn't use the square brackets?

Not sure what I did wrong, I wasn't aware of using any indentation in my response. Is it because I didn't use the square brackets?

Sorry, not you, I mean mahela007's code. :)

There is also line = line[:-1] to remove the last character.
I think vegaseat meant the indentation of your python source code. It's better to indent your code with space characters instead of tab characters. You should configure your editor so that it prints 4 space characters when you hit the tab key (4 is standard, other values are possible).

I find that best practice is to always use strip() on lines that I read in from files. This gets rid of all leading and trailing white-space (tabs, spaces, newlines, etc.)

Also, here's a rewrite of your code... I removed the tabs and replaced them with spaces and also stripped out the unnecessary work that you were doing... Please look it over and if there's anything you don't understand, ask and we shall explain.

def rec_paths(file_name):
    f = open(file_name)
    g = f.readlines()	

    for each_line in g:
        if 'path' in each_line.strip():
            return( each_line.strip() )

print(rec_paths('C:\\Documents and Settings\\folderX\\Desktop\\t.txt'))

I find that best practice is to always use strip() on lines that I read in from files. This gets rid of all leading and trailing white-space (tabs, spaces, newlines, etc.)

Also, here's a rewrite of your code... I removed the tabs and replaced them with spaces and also stripped out the unnecessary work that you were doing... Please look it over and if there's anything you don't understand, ask and we shall explain.

def rec_paths(file_name):
    f = open(file_name)
    g = f.readlines()	

    for each_line in g:
        if 'path' in each_line.strip():
            return( each_line.strip() )

print(rec_paths('C:\\Documents and Settings\\folderX\\Desktop\\t.txt'))

thanks a lot. The code i posted above was pretty rough work and and I'm also a newbie. Thanks for your improvement to the code.
But What's all this about not using tabs? Should I press the space key 4 times instead?
(The code in my first post has used two tabs instead of one. I am positive I pressed the tab key only once. I did the editing in 'geany' and while I was editing everything looked alright. All the double tabs appear when i paste the code into some other window)

EDIT:
I just noticed that your code will return the line containing the word 'path'. (please correct me if I am wrong.) However I want the code to return the next line.
for example if the code was run on a file containing the following lines of text:

1. path
2. line one
3. line two

it should return "line one","line two"

One other question:
does the strip or rstrip statement modify the original string or does it provide a temporary output?

You can do it this way

def rec_paths(file_name):
    f = open(file_name)
    for line in f:
        if 'path' in line:
            x, y = f.next(), f.next()
            return (x, y)

This will return a pair containing the 2 lines after the first line containing 'path', or None if there is no such line. Also if there is less than 2 lines after 'path', this will raise a StopIteration exception.

EDIT: strip and rstrip return a new string. A string is immutable in python: it cannot be modified by a function.

You can do it this way

def rec_paths(file_name):
    f = open(file_name)
    for line in f:
        if 'path' in line:
            x, y = f.next(), f.next()
            return (x, y)

This will return a pair containing the 2 lines after the first line containing 'path', or None if there is no such line. Also if there is less than 2 lines after 'path', this will raise a StopIteration exception.

EDIT: strip and rstrip return a new string. A string is immutable in python: it cannot be modified by a function.

Ooops ! I forgot the immutable thing.
Thanks a lot! Problem solved ...

when I run the program I get an error saying" textwrapper object has not method next" or something like that. What is this error?

sorry, replace f = open(filename) by f = iter(open(filename)) .

sorry, replace f = open(filename) by f = iter(open(filename)) .

what does that do?

f = iter(open(filename))

In python, some objects are "iterable" They can be used in "for" constructs

# this syntax is possible if the object X is iterable
for item in X:
    dothis()

Iterable objects usually have a method __iter__ which is called when you write the expression iter(X) . This method (or this expression) return an "iterator".
An iterator Z has a method "next" which returns the next item in an iteration. If there is no such item, the method next raises the exception StopIteration. An iterator also has a method __iter__ which returns itself.
Here is an example

>>> L = list(range(3))
>>> L
[0, 1, 2]
>>> Z = iter(L)  # a list is iterable
>>> Z  # Z is an iterator
<listiterator object at 0xb7d586ac>
>>> Z.next()
0
>>> Z.next()
1
>>> Z.next()
2
>>> Z.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> Z is iter(Z)  # iter is a no-op on iterators
True

A file object f opened for reading is iterable. iter(f) returns an iterator over the lines of the file (without the trailing newlines (unlike readline)).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.