Why is target.write ignoring my %r formatting? - python

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

Related

Can't break a line with string in optparse

I am trying to break a line with \n with optparse. Example: line1 \n line2
But when I type \n it doesn't break it just prints it as line1 \n line2, instead of doing a break. Here is my code:
import optparse
import sys
def main():
progparse = optparse.OptionParser("usage " + "--message <text here>")
progparse.add_option("--message", dest="msg_txt", type="string", help="Type the message you want to send")
msg_txt = ""
if (options.msg_txt == None):
print(progparse.usage)
sys.exit()
print(options.msg_txt)
if __name__ == '__main__':
main()
If I just do a simple print statment with \n then it will break the line, why doesn't it do it when using optparse?
option1, use real new line in your input:
$ python3 test.py --message "line1
> line2
> line3"
line1
line2
line3
option2, eval \n as real new line with ast.literal_eval:
print(ast.literal_eval('"' + options.msg_txt + '"'))
note this may raise an exception for ill-formed input.

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

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

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

Write user input to file python

I can't figure out how to write the user input to an existing file. The file already contains a series of letters and is called corpus.txt . I want to take the user input and add it to the file , save and close the loop.
This is the code I have :
if user_input == "q":
def write_corpus_to_file(mycorpus,myfile):
fd = open(myfile,"w")
input = raw_input("user input")
fd.write(input)
print "Writing corpus to file: ", myfile
print "Goodbye"
break
Any suggestions?
The user info code is :
def segment_sequence(corpus, letter1, letter2, letter3):
one_to_two = corpus.count(letter1+letter2)/corpus.count(letter1)
two_to_three = corpus.count(letter2+letter3)/corpus.count(letter2)
print "Here is the proposed word boundary given the training corpus:"
if one_to_two < two_to_three:
print "The proposed end of one word: %r " % target[0]
print "The proposed beginning of the new word: %r" % (target[1] + target[2])
else:
print "The proposed end of one word: %r " % (target[0] + target[1])
print "The proposed beginning of the new word: %r" % target[2]
I also tried this :
f = open(myfile, 'w')
mycorpus = ''.join(corpus)
f.write(mycorpus)
f.close()
Because I want the user input to be added to the file and not deleting what is already there, but nothing works.
Please help!
Open the file in append mode by using "a" as the mode.
For example:
f = open("path", "a")
Then write to the file and the text should be appended to the end of the file.
That code example works for me:
#!/usr/bin/env python
def write_corpus_to_file(mycorpus, myfile):
with open(myfile, "a") as dstFile:
dstFile.write(mycorpus)
write_corpus_to_file("test", "./test.tmp")
The "with open as" is a convenient way in python to open a file, do something with it while within the block defined by the "with" and let Python handles the rest once you exit it (like, for example, closing the file).
If you want to write the input from the user, you can replace mycorpus with your input (I am not too sure what you want to do from your code snippets).
Note that no carriage return is added by the write method. You probably want to append a "\n" at the end :-)

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

Categories

Resources