Function call doesnt work python - python

Im trying to print palindrome words in a file (where each line is a word) in python.
Thats what I have so far:
I have to work in Unix so I wrote my script in file palindrome.py as below:
#!/usr/bin/python
def isPalindrome(a):
if a == a[::-1]:
print a
with open ('fileName') as f:
for line in f:
isPalindrome(line)
When I run the file it doesn't print anything even-though there are palindrome words in my file. I think the problem is related to my function call because if instead of isPalindrome(line) I have isPalindrome('aha') it will print aha. I tried to print each line after the for loop but that works as well. It does print all the lines of the file. So line does get different values so I guess there might be something related to the call but I am failing to find out what.

You need to strip newlines from the end of your lines. Try call as isPalindrome(line.strip()).

Attention: file.readlines() does not wrap end line characters!!
so if in you file you have aha in one line, the line will be aha\n (with the new line char...)...
I suggest use of replace() string method.
Your code:
#!/usr/bin/python
def isPalindrome(a):
if a == a[::-1]:
print a
with open ('fileName') as f:
for line in f:
isPalindrome(line.replace('\n', '').replace("\r", "")) # replace carriage return / line feed chars

Related

First line a of a file not printing in a function

I was looking around but I couldn't find a question similar that also includes functions.
My PYTHON code is supposed to output every line in a text file, but in uppercase. I understand how you'd do this without functions, but I have to use a function.
It prints out everything in uppercase, but the first line, I think its because of the f.read ?? I've played around with it, but then it just outputs nothing. I also tried a different method, but it created an entirely new file, and that's not the result I need. Any ideas on how to go about this?
Here's what I did
def uppercase():
with open("qwerty.txt", "r") as f:
for line in f:
line = f.read()
line = line.upper()
return line
print(uppercase())
You don't need to do line = f.read() since you're already getting the line with your loop variable. This is why your program doesn't output the first line.
Moreover, the return is outside the loop so that means you will only return the last value of line. My guess is that your function should directly print all the lines in uppercase, it's ok if it returns nothing.
So basically, you should end up with a function like this:
def uppercase(file):
with open(file, "r") as f:
for line in f:
line = line.upper()
print(line)
uppercase("query.txt")

Unable to read multiline files in python using readline()

The following code is not working properly. It is unable to read multiline files in python using readline().
myobject=open("myfile.txt",'r')
while ((myobject.readline())):
print(myobject.readline())
myobject.close()
It just prints the first line and then newlines. I don't understand why?
It's because readline reads one line at a time, your code will still print a new line because readline keeps trailing newlines.
The way to fix would be to do this:
with open("myfile.txt", 'r') as f:
for line in f:
print(line)
readline() returns the line that it is currently pointing to and moves to the next line. So, the calls to the function in the while condition and in the print statement are not the same. In fact, they are pointing to adjacent lines.
First, store the line in a temporary variable, then check and print.
myobject = open('myfile.txt')
while True:
line = myobject.readline()
if line:
print(line)
else:
break
When you open the file in 'r' mode, the file object returned points at the beginning of the file.
Everytime you call readline, a line is read, and the object now points to the next line in the file
Since your loop condition also reads the file and moves it to the next line, you are getting lines only at even places, like line no 2, 4, 6. Line Numbers, 1, 3, 5, ... will be read by while ((myobject.readline())): and discarded.
A simple solution will be
myobject = open("myfile.txt",'r')
for line in myobject:
print(line, end='')
myobject.close()
OR for your case, when you want to use only readline()
myobject = open("myfile.txt",'r')
while True:
x = myobject.readline()
if len(x) == 0:
break
print(x, end='')
myobject.close()
This code works, because readline behaves in the following way.
According to python documentation, https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

Reading through a .m File and Python keeps reading a character in the .m File as a line?

I am trying to read the text within a .m file in Python and Python keeps reading a single character within the .m file as a line when I use file.readline(). I've also had issues with trying to remove certain parts of the line before adding it to a list.
I've tried adjusting where the readline is on for loops that I have set up since I have to read through multiple files in this program. No matter where I put it, the string always comes out separated by character. I'm new to Python so I'm trying my best to learn what to do.
# Example of what I did
with open('MyFile.m') as f:
for line in f:
text = f.readline()
if text.startswith('%'):
continue
else:
my_string = text.strip("=")
my_list.append(my_string)
This has only partially worked as it will still return parts of lines that I do not want and when trying to format the output by putting spaces between new lines it output like so:
Expected: "The String"
What happened: "T h e S t r i n g"
Without your input file I've had to make some guesses here
Input file:
%
The
%
String
%
Solution:
my_list = []
with open('MyFile.m') as f:
for line in f:
if not line.startswith('%'):
my_list.append(line.strip("=").strip())
print(' '.join(my_list))
The readLine() call was unnecessary as the for loop already gets you the line. The empty if was negated to only catch the part that you cared about. Without your actual input file I can't help with the '=' part. If you have any clarifications I'd be glad to help further.
As suggested by Xander, you shouldn't call readline since the for line in f does that for you.
my_list = []
with open('MyFile.m') as f:
for line in f:
line = line.strip() # lose the \n if you want to
if line.startswith('%'):
continue
else:
my_string = line.strip("=")
my_list.append(my_string)

How do I compare a word from a text file?

I have a text file like below:
/john
/peter
/Sam
/Jennefer
Using the the following script:
keyword_file = open(text_file)
j = keyword_file.readlines()
for i in range(len(j)):
if j[i] == "/peter":
print "yes"
although /peter is in the text file I don't get the printed yes. However when I delete "/"s , "yes" is printed. What is the problem with it?
First off you're not just looking for /peter you're looking for /peter\n.
Second, there's a lot here that you can do to improve your script:
Use with instead of forcing yourself to open and close your file:
with open(text_file) as fp:
<your code here>
Instead of reading the entire file, read it line by line:
for line in fp:
<your business logic here>
compare your string using is instead of ==: See this SO answer why I'm wrong here
if line is '/peter\n':
<condition if peter is found>
Here's the combined script that match what you're trying to do:
with open(text_file) as fp:
for line in fp:
if line == '/peter\n':
print("yes") # please use print(<what you want to print here>) instead of print <what you want here> for compatibility with 3.0 and readability.
The problem here is that you are looking for an exact match on the whole line. This includes any special ascii characters that may be included; such as a newline character.
If you instead read the text, and split it by line, and iterate over the result your code would work:
result = keyword_file.read()
for line in result.split('\n'):
if line == "/peter":
print "yes"
As an alternative you could use
for line in keyword_file:
if line.startswith("/peter"): # or "/peter" in line
print "yes"
If you want to avoid storing the whole file in memory, and still have a clean if statement you can use strip() to remove any unnecessary special characters or spaces.
with open(file_name) as file_obj:
for line in file_obj:
if line.strip() == '/peter':
print "yes"

Python: Prevent fileinput from adding newline characters

I am using a Python script to find and replace certain strings in text files of a given directory. I am using the fileinput module to ease the find-and-replace operation, i.e., the file is read, text replaced and written back to the same file.
The code looks as follows:
import fileinput
def fixFile(fileName):
# Open file for in-place replace
for line in fileinput.FileInput(fileName, inplace=1):
line = line.replace("findStr", "replaceStr")
print line # Put back line into file
The problem is that the written files have:
One blank line inserted after every line.
Ctrl-M character at the end of every line.
How do I prevent these extra appendages from getting inserted into the files?
Your newlines are coming from the print function
use:
import sys
sys.stdout.write ('some stuff')
and your line breaks will go away
Use
print line,
or
file.write(line)
to fix extra newlines.
As of [Ctrl]-[M] - that is probably caused by input files in DOS encoding.
Instead of this:
print line # Put back line into file
use this:
print line, # Put back line into file
Change the first line in your for loop to:
line = line.rstrip().replace("findStr", "replaceStr")
Due to every iteration print statement ends with newline, you are getting blank line between lines.
To overcome this problem, you can use strip along with print.
import fileinput
def fixFile(fileName):
for line in fileinput.FileInput(fileName, inplace=1):
line = line.replace("findStr", "replaceStr")
print line.strip()
Now, you can see blank lines are striped.
For the update on Python 3.4, you can just use:
print(line, end = '')
to avoid the insertion of a new line.

Categories