How to get a script to read and write a file? - python

I'm completing exercise 16 from Learn Python the Hard Way and it's asking this question:
Write a script similar to the last exercise that uses read and argv to
read the file you just created.
I'm attempting to use the 'read' function in order to have the script automatically run and display the text file that the script creates. But nothing shows up when I run everything, it's just an extra blank space before "close it". How do I get it to display anything?
from sys import argv
script, filename = argv
txt = open(filename)
print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file."
target.truncate()
print "Need 3 lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "Write these to a file"
target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))
print txt.read()
print "Close it."
target.close()

You should close the file after writing and then open it again for reading:
from sys import argv
script, filename = argv
print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."
raw_input("?")
print "Opening the file..."
with open(filename, 'w') as target:
print "Truncating the file."
target.truncate()
print "Need 3 lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "Write these to a file"
target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))
txt = open(filename)
print txt.read()
print "Close it."
target.close()
The second version (without "with as" structure):
from sys import argv
script, filename = argv
print "Erase %r" % filename
print "hit CTRL-C (^C)."
print "hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file."
target.truncate()
print "Need 3 lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "Write these to a file"
target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))
print "Close it."
target.close()
txt = open(filename)
print txt.read()

Related

Python: printing strings from another file

I want to call a file, erase its data, write new lines and print it.
Below is my program and its output.
from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
new = text.read()
old = text.readlines()
print "%s" %(new)
print old
print text.readlines()
text.close()
Output:
[]
[]
So, your error (by your comments is that it isn't letting you read).
This is because your trying to read using a file pointer which was used to open the file in write mode.
from sys import argv
string, filename = argv
with open(filename, 'w') as text:
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
with open(filename, 'r') as text:
...
So adding seek(0) will do the job here.
seek(0) set the pointer at the beginning.
Here's the working code:
from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
text.seek(0)
new = text.read()
text.seek(0)
old = text.readlines()
print "%s" %(new)
print old
text.seek(0)
print text.readlines()
text.close()
Output:
hey
I was doing just fine before I met you
I drink too much and that's an issue but I'm okay
['hey\n', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"]
['hey\n', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"]

In python why it won't print without newline

I am new to learning python. I don't understand why print command will output all variables on screen but write command to file only writes 2 first two variables.
print "Opening the file..."
target = open(filename, 'a+')
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
line4 = line1 + "\n" + line2 + "\n" + line3
# This command prints all 3 (line1,line2,line3) variables on terminal
print line4
#This command only writes line1 and line2 variables in file
target.write(line4)
print "close the file"
target.close()
The OS normally flushes the write buffer after a newline.
When you open(filename, 'a+') the file, these same rules apply by default.
From the docs: https://docs.python.org/2/library/functions.html#open
The optional buffering argument specifies the file’s desired buffer
size: 0 means unbuffered, 1 means line buffered, any other positive
value means use a buffer of (approximately) that size (in bytes). A
negative buffering means to use the system default, which is usually
line buffered for tty devices and fully buffered for other files. If
omitted, the system default is used.
Call target.close() to ensure everything is written out ("flushed") to the file (as per the comment below, close flushes for you). You can manually flush with target.flush().
print "Opening the file..."
target = open(filename, 'a+')
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
line4 = line1 + "\n" + line2 + "\n" + line3
# This command prints all 3 (line1,line2,line3) variables on terminal
print line4
target.write(line4)
target.close() #flushes
Alternatively, using the with keyword will automatically close the file when we leave the with block: (see What is the python keyword "with" used for?)
print "Opening the file..."
with open(filename, 'a+') as target:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
line4 = line1 + "\n" + line2 + "\n" + line3
# This command prints all 3 (line1,line2,line3) variables on terminal
print line4
target.write(line4)

Error: Getting symbols in python output

#I wrote the following code for making a text editor.
print "This is a simple text editor"
from sys import argv
script, name = argv
print "You have selected the file : %s" %name
print "Opening the file...."
t = open(name, 'r+')
print "The contents of the file are"
print t.read()
f = open(name, 'w+')
print "Now we will truncate the file and empty it of it's contents"
f.truncate()
print "Now let us write something into our file\n"
x = raw_input('What do you want to write\n') #Works fine till here
f.write(x)
print "Now we read our file again"
print f.read()
print "And finally we close the file"
f.close()
After the promp to write something in the file, the script goes awry and produces strange symbols instead of the typed text. Please help
You need to close and re-open your file.
print "This is a simple text editor"
from sys import argv
script, name = argv
print "You have selected the file : %s" %name
print "Opening the file...."
t = open(name, 'r+')
print "The contents of the file are"
print t.read()
t.close() ##########
f = open(name, 'w+')
print "Now we will truncate the file and empty it of it's contents"
f.truncate()
print "Now let us write something into our file\n"
x = raw_input('What do you want to write\n') #Works fine till here
f.write(x)
f.close() ##########
f = open(name, 'r+') ##########
print "Now we read our file again"
print f.read()
print "And finally we close the file"
f.close()

create a file from user input

Anyone can help me on this task. I'm new to Python. I'm trying to accomplished this:
The filename should be hardcode name called: Server_Information.txt and and the second column should be inserted by the user input but the date stamp.
Built By : john doe
Build Date: %d%m%y
Build Reason: Playground
Requestor: john doe
Maybe I can use this test script but the first column does not show in the final test file.
Thank you for anyone it helps
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("Built By : ")
line2 = raw_input("Build Date: %d%m%y ")
line3 = raw_input("Build Reason: ")
line4 = raw_input("Requestor: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
target.write(line4)
print "And finally, we close it."
target.close()
Try closing and reopening the file after the truncate()
target.close()
target = open(filename, 'w')
# ask for user input here
# and close file
Try to write this, because now you do not record the invitation as a file.
target.write('%s: %s\n' % ('Built By', line1))
target.write('%s: %s\n' % ('Build Date', line2))
target.write('%s: %s\n' % ('Build Reason', line3))
target.write('%s: %s\n' % ('Requestor', line4))
Since raw_input returns only the input entered by user, not include the messages you used to prompt, so you need to add those messages to line1 manually, like this:
line1 = "Built By : " + raw_input("Built By : ")
And for line2 I think you want to generate it automatically instead of asking user to enter, you can do it like this:
line2 = "Build Date: " + time.strftime("%d%m%Y", time.localtime())

Why is target.write ignoring my %r formatting?

I'm trying to write a program similar to this guy's Learn Python the Hard Way program, near the top of the page.
http://learnpythonthehardway.org/book/ex16.html
This is my version below. But it tells me off for using "%r" at the end, why does it do that? I thought that's what you're meant to do in parenthesis.
# -- coding: utf-8 --
from sys import argv
script, filename = argv
print "Would you like file %r to be overwritten?" % filename
print "Press RETURN if you do, and CTRL-C otherwise."
raw_input('> ')
print "Opening the file ..."
target = open(filename, 'w')
target.truncate()
print "Now type three lines to replace the contents of %r" % filename
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "The lines below have now overwritten the previous contests."
target.write("%r\n%r\n%r") % (line1, line2, line3)
target.close()
You need to place the % operator directly after the format string. Take the parenthesis here:
target.write("%r\n%r\n%r") % (line1, line2, line3)
# --^
And move it to the end of the line:
target.write("%r\n%r\n%r" % (line1, line2, line3))
# --^
Also, I would like to mention that performing string formatting operations with % is frowned upon these days. The modern approach is to use str.format:
target.write("{0!r}\n{1!r}\n{2!r}".format(line1, line2, line3))

Categories

Resources