Python reading file but the command line prints a blank line - python

I am doing Learn Python the Hard Way and am on exercise 16. The study drill says to write a script using read and argv.
My code is as follows:
from sys import argv
script, file_name, pet_name = argv
print "Ah, your pet's name is %r." %pet_name
print "This will write your pet's name in a text file."
print "First, this will delete the file. "
print "Proceeding..."
writefile = open(file_name, 'w')
writefile.truncate()
writefile.write(pet_name)
writefile.close
raw_input("Now it will read. Press ENTER to continue.")
readfile = open(file_name, "r")
print readfile.read()
The code works until the end. When it says to print the file, the command line gives a blank line.
PS C:\Users\[redacted]\lpthw> python ex16study.py pet.txt jumpy
Ah, your pet's name is 'jumpy'.
This will write your pet's name in a text file.
First, this will delete the file.
Proceeding...
Now it will read. Press ENTER to continue.
PS C:\Users\[redacted]\lpthw>
I am not sure why the script is just printing a blank file.

You never called the writefile.close() method:
writefile.write(pet_name)
writefile.close
# ^^
Without closing the file, the memory buffer to help speed writing never gets flushed and the file effectively remains empty.
Either call the method:
writefile.write(pet_name)
writefile.close()
or use the file as a context manager (with the with statement) to have Python close it for you:
with open(file_name, 'w') as writefile:
writefile.write(pet_name)
Note that the writefile.truncate() call is entirely redundant. Opening a file in write mode ('w') always truncates the file already.

Related

Python file not appending on Raspberry Pi

I'm quite new to Python and Pi'ing, and would like some help with appending a text file on a Raspberry Pi. My script will call a GET or a POST REST API and write the time, status and reason for each call.
I got the call information from grepit's comment in Simple URL GET/POST function in Python and it works great.
For appending my file, I use the following code:
#...Some working code...
dateNow = datetime.datetime.now()
string = ("\n" + dateNow.strftime("%c") + " - " + str(response.status) +
": " + response.reason + "\n")
with open('MyCallLog.txt', 'a+') as file:
file.write(string)
What I have read regarding similar issues, is that the file is not closed or flushed. However, if I try to debug using print(file.read()) outside the 'with' I get an error that is file is already closed and debugging inside the with displays nothing. I also tried it without the with and specifically stating file.close(). I have debugged the string variable using print(string) and it displays as intended.
Any suggestions?
Final notes:
I am aware that opening a file as 'a+' does open it in read and write mode. This is currently only for my debugging purposes.
When a file is opened in append mode using "a+" the cursor is positioned at the end of the file. That is why a call to .write() will append to the end of the file instead of overwriting it.
When you call file.read() in the with block, it is reading the file from the last character onwards, which is why your print output is empty.
To print the content you need to seek to the beginning of the file.
with open("myfile.txt", "a+") as file:
file.write("some_text")
file.seek(0)
print(file.read()) # "some_text"
Better yet, just open the file again for your debugging.
with open("myfile.txt", "a+") as file:
file.write("some_text")
with open("myfile.txt", "r") as file:
print(file.read())
Your code to append was actually correct. There should be a file in the CWD with all of your attempts in it.
Also, the reason that you get an error when you try to call .read() outside of the with block is because file.close() is implicitly called when the block exits.
open() returns a context manager. You can read about context managers in python here. They are very useful and great to know about. I write new context managers often at my job.

Reading and Writing in Same Script

I am currently on Excercise 16 in Learn Python the Hard Way and i'm having a problem with my code where it will write onto the file, but my final print command does not print the contents of the file onto the console. On my command line, it just comes up with a couple of lines of blank space.From my understand "r+"opens it in read and write mode, but the computer cannot to read it.
Could someone tell me whats wrong with it please? Any help would be appreciated :)
from sys import argv
script, file = argv
print "The name of the file is %s" % file
filename = open(file,"r+")
print "First we must write something in it "
print "Do you want to continue?Press CTRL-C if not."
raw_input()
print "Type the first line of the text"
line1 = raw_input(">")+"\n"
print "Type the second line of text"
line2 = raw_input(">")+"\n"
print "Type the third line of text"
line3 = raw_input(">")+"\n"
sum_line = line1 + line2 + line3
print "Now I will write it to the file"
filename.write(sum_line)
print "The file now says:"
#This line here does not print the contents of the file
print filename.read()
filename.close()
As included in the first answer, after writing the offset will be pointing to the end of the file. However, you don't need to close the file and reopen it. Rather do this before reading it :
filename.seek(0)
That will reset the offset at the start of the file.
Then simply read it.
filename.read()
Since you wrote into the file, the offset after writing will point to the end of the file. At that point, if you want to read the file from the beginning you'll have to close it and re-open it.
By the way, since Python 2.5 the with statement is supported and recommended to use, for example:
with open('yourfile', 'r') as f:
for line in f:
...
Using with will take care of closing the file for you!
Without having to close then reopen the file you can add filename.seek(0) which will take it back to the top of the file.
filename = open('text.txt',"r+")
print(filename.read())
lin = input()
filename.write(lin)
filename.seek(0) # take it back to top, 0 can be changed to whatever line you want
print(filename.read())
filename.close()

Attempting to write to a file in Python makes the file go blank

I'm relatively new to Python, and I'm trying to create a piece of code in Python that looks through each line of a text file for a certain value, inputted by the user, then replaces a line with a new one created by the code. However, when I try the code, the file goes blank. I've got an f.close() but the code still won't write.
Here is my code:
import fileinput
f = open("task3.txt", "w+")
name = input("What is your name?")
lines = f.readlines()
print(lines)
for i in lines:
splitlines = i.split(":")
print(splitlines)
splitnums = splitlines[1].split(", ")
print(splitnums)
for i in splitnums:
i = int(i)
edit = input('Would you like to edit this entry?')
if edit == "Yes":
valueNew = input("Which new value would you like to add?")
del(splitnums[2])
splitnums.append(splitnums[1] + "\n")
splitnums[1] = splitnums[0] + ", "
splitnums[0] = valueNew + ", "
print(splitnums)
numstring = ''.join(splitnums)
splitlines[1] = ": "
splitlines.append(numstring)
newval = ''.join(splitlines)
print(newval)
f.write(newval)
else:
print("Okay.")
f.close()
You will have to read the entire file, then change the content before writing again, as w clears the file contents. If appending to (adding to the end of) the file suffices, you can change the mode argument to a to open the file in append mode.
You should also consider using with instead of manually closing the file:
with open('file.txt', 'w') as f:
...
, as this closes the file and cleans up regardless of errors thrown etc.
Mode w+ means "open the file for writing, truncating it first, and also let me read it"
So, it's doing exactly what you asked.
If you want to open the file for reading, but also let you write it, that's spelled r+. Or, in Python 3.0+, you can also just use plain +.
The docs for open even include examples of different modes that explain exactly what you're asking:
The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.
Or, for the 2.x version:
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file.
That's the difference between r+ and w+ (or r+b and w+b): use the r one when you don't want truncation.

How do I print the content of a .txt file in Python?

I'm very new to programming (obviously) and really advanced computer stuff in general. I've only have basic computer knowledge, so I decided I wanted to learn more. Thus I'm teaching myself (through videos and ebooks) how to program.
Anyways, I'm working on a piece of code that will open a file, print out the contents on the screen, ask you if you want to edit/delete/etc the contents, do it, and then re-print out the results and ask you for confirmation to save.
I'm stuck at the printing the contents of the file. I don't know what command to use to do this. I've tried typing in several commands previously but here is the latest I've tried and no the code isn't complete:
from sys import argv
script, filename = argv
print "Who are you?"
name = raw_input()
print "What file are you looking for today?"
file = raw_input()
print (file)
print "Ok then, here's the file you wanted."
print "Would you like to delete the contents? Yes or No?"
I'm trying to write these practice codes to include as much as I've learned thus far. Also I'm working on Ubuntu 13.04 and Python 2.7.4 if that makes any difference. Thanks for any help thus far :)
Opening a file in python for reading is easy:
f = open('example.txt', 'r')
To get everything in the file, just use read()
file_contents = f.read()
And to print the contents, just do:
print (file_contents)
Don't forget to close the file when you're done.
f.close()
Just do this:
>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
... print f.read()
This will print the file in the terminal.
with open("filename.txt", "w+") as file:
for line in file:
print line
This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop
How to read and print the content of a txt file
Assume you got a file called file.txt that you want to read in a program and the content is this:
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
You can read this content: write the following script in notepad:
with open("file.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
save it as readfile.py for example, in the same folder of the txt file.
Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:
C:\examples> python readfile.py
You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).
output
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
to input a file:
fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'
to output this file you can do:
for element in fin:
print element
if the elements are a string you'd better add this before print:
element = element.strip()
strip() remove notations like this: /n
print ''.join(file('example.txt'))
This will give you the contents of a file separated, line-by-line in a list:
with open('xyz.txt') as f_obj:
f_obj.readlines()
It's pretty simple
#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)
Presenting snapshot from my visual studio IDE.
single line to read/print contents of a file
reading file : example.txt
print(open('example.txt', 'r').read())
output:
u r reading the contents of example.txt file
Reading and printing the content of a text file (.txt) in Python3
Consider this as the content of text file with the name world.txt:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!
First we will open this file by doing this:
file= open("world.txt", 'r')
Now we will get the content of file in a variable using .read() like this:
content_of_file= file.read()
Finally we will just print the content_of_file variable using print command.
print(content_of_file)
Output:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!

Cannot read file after writing to it

I am currently reading "Learn Python the hard way" and have reached chapter 16. I can't seem to print the contents of the file after writing to it. It simply prints nothing.
from sys import argv
script, filename = argv print "We are going to erase the contents of %s" % filename print "If you don\'t want that to happen press Ctrl-C"
print "If you want to continue press enter"
raw_input("?") print "Opening the file..." target = open(filename, "w")
print "Truncating the file..." target.truncate()
print "Now i am going to ask you for 3 lines"
line_1 = raw_input("Line 1: ")
line_2 = raw_input("Line 2: ")
line_3 = raw_input("Line 3: ")
final_write = line_1 + "\n" + line_2 + "\n" + line_3
print "Now I am going to write the lines to %s" % filename
target.write(final_write)
target.close
print "This is what %s look like now" %filename
txt = open(filename)
x = txt.read() # problem happens here
print x
print "Now closing file"
txt.close
You're not calling functions target.close and txt.close, instead you're simply getting their pointers. Since they are functions (or methods, to be more accurate) you need () after the function's name to call it: file.close().
That's the problem; you open the file in write mode which deletes all the content of the file. You write in the file but you never close it, so the changes are never committed and the file stays empty. Next you open it in read mode and simply read the empty file.
To commit the changes manually, use file.flush(). Or simply close the file and it will be flushed automatically.
Also, calling target.truncate() is useless, since it's already done automatically when opening in write mode, as mentioned in the comments.
Edit: Also mentioned in the comments, using with statement is quite powerful and you should use it instead. You can read more of with from http://www.python.org/dev/peps/pep-0343/, but basically when used with files, it opens the file and automatically closes it once you unindent. This way you don't have to worry about closing the file, and it looks much better when you can clearly see where the file is being used, thanks to the indentation.
Quick example:
f = open("test.txt", "r")
s = f.read()
f.close()
Can be done shorter and better looking by using with statement:
with open("test.txt", "r") as f:
s = f.read()

Categories

Resources