Reading from file - python

I am a beginner and just started learning Python couple days ago (yay!)
so i've come across a problem. when i run, this code outputs everything but the text (txt in file is numbers 0-10 on seperate lines)
def output():
xf=open("data.txt", "r")
print xf
print("opened, printing now")
for line in xf:
print(xf.read())
print("and\n")
xf.close()
print("closed, done printing")

You don't use line, try:
with open('data.txt') as f:
for line in f:
print line

This should print out each number on its own line, like you want, in a lot less code, and more readable.
def output():
f = open('data.txt', 'r').read()
print f

When you used for line in xf: you basically already iterated over the file, implicitly reading each line.
All you need to do is print it:
for line in xf:
print(line)

The reason you aren't seeing the line output is because you aren't telling it to output the line. While iterating over values of line, you print xf.read(). The following is your function rewritten with this in mind. Also added is the use of a with statment block to automatically close the file when you're done with it.
(Using xf.close() is not wrong, just less pythonic for this example.)
def output():
with open("data.txt", "r") as xf:
print xf
print("opened, printing now")
for line in xf:
print(line)
print("and\n")
print("closed, done printing")

You have read the line of text into the variable line in the code for line in xf: so you need to show that e.g. print(line)
I would look at tutorials like the python.org one

Related

Why "while loop" does not run in txt file reading in Python?

I have the following code which reads txt file.
def get_line(filepath):
f = open(filepath, "r")
while True:
line = f.readline()
print(line)
f.close()
print ("Start...")
get_line("/path/to/file/textfile.txt")
print ("Stop...")
The code runs without the "while" loop. Once I add the while loop, the terminal just displays a black screen with no error messages and the program runs continiously.
Why does this happen?
f.readline() on a file open in text mode returns the empty string when it reaches the end of the file; the black screen is the infinite series of prints that produce a newline and nothing else.
You don't want a while loop for this case generally; the Pythonic solution is:
def get_line(filepath):
with open(filepath, "r") as f: # Use with to manage, so manual close not needed
for line in f: # Files are iterables of their lines
print(line) # Change to print(line, end='') to avoid added blank lines
# or use sys.stdout.write(line)
Or if you must use a while:
def get_line(filepath):
with open(filepath, "r") as f:
# Loop ends when line ends up empty
# Relies on 3.8+'s assignment expression, aka walrus operator
while line := f.readline():
print(line)
The pre-walrus version of the while loop approach would be:
while True:
line = f.readline()
if not line:
break
print(line)
But in practice, the for loop approach is almost always what you want.
If you need to read everything inside of that text file, you don't need to use while True.
You are not giving it a way to get out of that loop.
This should work as well:
with open('/path/to/file/textfile.txt) as f:
lines = f.read()
print(lines)
This does pretty much same thing you want as well!
You need check eof of a file, otherwise it will run forever until shutdown your computer.
For instance:
def get_line(filepath):
f = open(filepath, "r")
while True:
line = f.readline()
print(line)
if not line:
print('line is at the eof')
break
f.close()
print ("Start...")
get_line("A.txt")
print ("Stop...")
You are reading the file one line at a time in each iteration in the while loop. After reading all of the lines, you reach the end of the file. There is no more data/lines to read, what happens next? .readline() will return empty string.
Since the program runs fast enough, you probably won't see the lines of the file which actually have been loaded but are above of the empty lines. So the black screen is because of that. Blank lines immediately fill the screen.
Assuming you have 4-5 lines in your text file, run this to see this in action:
from time import sleep
def get_line(filepath):
f = open(filepath, "r")
while True:
line = f.readline()
print(repr(line), flush=True)
sleep(0.5)
f.close()
print("Start...")
get_line("text.txt")
print("Stop...")
I added repr() so that you can see the empty strings and sleep(0.5) so that you could see what's going on.
The True will produce an infinite loop. Try this instead
def get_line(filepath):
with open(filepath, "r") as f:
for line in f.readlines():
print(line)

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")

get distinct values from file via python

everyone!
I have one file containing one column with only numbers (Paramkey.txt) and i need to read the file and get distinct values and write them in another .txt file. Can someone help with the code? So far the code looks like this
infile=open("Paramkey.txt", "r")
outfile=open("distkey.txt", "w")
for line in infile:
outfile.write(set(infile)
else:
pass
infile.close()
outfile.close()
And i get Syntax error, something with the else statement.
So i managed to finish the program and it's working:
infile=open("Paramkey.txt", "r")
outfile=open("distkey.txt", "w")
for line in infile:
output=set(line.strip() for line in infile)
print >> outfile, "distincts:", output
infile.close()
outfile.close()
and i just want to add i used the "print >>" instead of "print()" statement, because my python is version 2.7.x not 3.x

Function call doesnt work 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

Combined effect of reading lines twice?

As a practice, I am learning to reading a file.
As is obvious from code, hopefully, I have a file in working/root whatever directory. I need to read it and print it.
my_file=open("new.txt","r")
lengt=sum(1 for line in my_file)
for i in range(0,lengt-1):
myline=my_file.readlines(1)[0]
print(myline)
my_file.close()
This returns error and says out of range.
The text file simply contains statements like
line one
line two
line three
.
.
.
Everything same, I tried myline=my_file.readline(). I get empty 7 lines.
My guess is that while using for line in my_file, I read up the lines. So reached end of document. To get same result as I desire, I do I overcome this?
P.S. if it mattersm it's python 3.3
No need to count along. Python does it for you:
my_file = open("new.txt","r")
for myline in my_file:
print(myline)
Details:
my_file is an iterator. This a special object that allows to iterate over it.
You can also access a single line:
line 1 = next(my_file)
gives you the first line assuming you just opened the file. Doing it again:
line 2 = next(my_file)
you get the second line. If you now iterate over it:
for myline in my_file:
# do something
it will start at line 3.
Stange extra lines?
print(myline)
will likely print an extra empty line. This is due to a newline read from the file and a newline added by print(). Solution:
Python 3:
print(myline, end='')
Python 2:
print myline, # note the trailing comma.
Playing it save
Using the with statement like this:
with open("new.txt", "r") as my_file:
for myline in my_file:
print(myline)
# my_file is open here
# my_file is closed here
you don't need to close the file as it done as soon you leave the context, i.e. as soon as you continue with your code an the same level as the with statement.
You can actually take care of all of this at once by iterating over the file contents:
my_file = open("new.txt", "r")
length = 0
for line in my_file:
length += 1
print(line)
my_file.close()
At the end, you will have printed all of the lines, and length will contain the number of lines in the file. (If you don't specifically need to know length, there's really no need for it!)
Another way to do it, which will close the file for you (and, in fact, will even close the file if an exception is raised):
length = 0
with open("new.txt", "r") as my_file:
for line in my_file:
length += 1
print(line)

Categories