Error: Getting symbols in python output - python

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

Related

I/O operation on closed file; trying to print on-screen after writing to a file

I'm trying to write the contents of the screen to a text file if the user selects that option. However, Python seems to want to print "Report Complete." to the report.txt file, which I told it to close. I want the "report complete" to display on the screen after it writes to the text file, and move on to the hashing function.
import wmi
import sys
import hashlib
c = wmi.WMI()
USB = "Select * From Win32_USBControllerDevice"
print ("USB Controller Devices:")
for item in c.query(USB):
print (item.Dependent.Caption)
print (" ")
print ("======================================")
report = input ("Would you like the results exported to a file? ")
if (report) == "yes":
file = open('report.txt', 'w')
sys.stdout = file
for item in c.query(USB):
print (item.Dependent.Caption)
file.close()
print ("Report complete.")
else:
print ("Job Complete.")
hashInput = input ("Would you like to hash the report? ")
if (hashInput) == "yes":
hash = hashlib.md5(open('report.txt', 'rb').read()).hexdigest()
print ("The MD5 hash value is:", (hash))
else:
print ("Job Complete.")
You set sys.stdout to a file, and then closed the file. That makes everything you try and print, which would normally go to stdout, try and go to a closed file. If I may suggest, don't reassign sys.stdout. It is not necessary.
if report == "yes":
with open('report.txt', 'w') as fout:
for item in c.query(USB):
print(item.Dependent.Caption, file=fout)
print("Report complete.")

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

learning Python the hard way argv and file

I am learning python from past weeks
from sys import argv
script,filename = argv
print "We're delete the file %r" %filename
print "If you want to stop ctrl+c (^c)"
print "Please hit enter to continue"
raw_input(">_")
print "Opening file..."
filen = open(filename,'w')
print "Truncating your file...."
filen.truncate()
print "now in your file %r" %filen
print "Writing time write something to your file"
line = raw_input("?")
print "write in progress..."
filen.write(line)
filen.write("\n end of document\n")
filen.close()
I want to view the contents of the file ,but when i use print filename or print filen it show name and open file on variable filen
you can read data using filen.read() or filen.readline() or filen.readlines()
1) read
fo = open(filename,read)
fo.seek(0, 0) #seek is used to change the file position.This requires only for read method
fo.read(10) #This reads 1st 10 characters
fo.close()
2) readline
fo = open(filename,read)
fo.readline() #This will read a single line from the file. You can add for loop to iterate all the data
fo.close()
3) readlines.
fo = open(filename,read)
fo.readline() #read all the lines of a file in a list
fo.close()
Below document will give you better idea.
https://docs.python.org/2/tutorial/inputoutput.html
If you want to print the content of the file you opened, just use: print filen.read().
At its simplest:
from sys import argv
script,filename = argv
with open(filename) as f:
print f.readlines()
which dumps the files contents
or:
from sys import argv
script,filename = argv
with open(filename) as f:
lines=f.readlines()
for line in lines:
print line
which prints the lines out 1 by 1

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