I'm following Zed A. Shaw's lpthw example 17 if you want to look at it https://learnpythonthehardway.org/book/ex17.html and it works just with only one line but not multiple (using terminal, windows powershell)
the original file says
"This is a test you are being tested why does it not work on multiple lines the 2nd line says see but capitalized
SEE"
the 2nd file that copied the text and pasted it using write command says this
"This is a test you are being tested why does it not work on multiple lines the 2nd line says see but capitalized
ऀ匀䔀䔀" I don't understand it i even copied his code and there isn't a single change in his or mine yet neither
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
out_file = open(to_file, 'w')
out_file.write(indata)
print "Alright, all done."
out_file.close()
in_file.close()`
I don't want to change the code much just because I know this works for a single line and beleive without much change it can work with an entire essay for example
Try setting the correct encoding for the file you are reading when you open it
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
You may be having this problem due to the difference in which new lines are handled in Windows vs Linux.
Have a look at : Handling \r\n vs \n newlines in python on Mac vs Windows
Related
I'm working through the "Learn python the hard way" book, I've run into a problem in the Second Exercise of the 16th study drill. I am using the newest version of python 3.
The code I wrote looks like this so far:
from sys import argv
script, filename = argv #we input the filename into argv
print ("We're going to erase %r." % filename) #tells us the name of the file we're deleting
print ("If you don't want that, hit CTRL-C (^C)")
print ("If you do want that, hit RETURN.")
input("?") #look into error unexpected EOF while parsing, I had to type "", if I don't program ends here
print ("Opening the file...")
target = open(filename, "w") #opens the file
print ("Truncating the file. Goodbye!")
target.truncate() #erases everything in the file
print ("Now I'm going to ask you for three lines")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
#summary: we create 3 input variables we'll use under here
print ("I'm going to write these to the file.")
target.write(line1) #summary: we write in the terminal what we want in our file and use that
target.write("\n") #we also have this newline command after every line to make sure it's not all in one line
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
#The default code is done at this point
print ("Type the filename again and I'll read it back to you or press CTRL + C (^C) to exit")
file_again = input(">")
print (file_again) #Added to try to see what this gave me, it gives nothing back --- isn't working, why?
print ("Now I'll read the file back to you!") #This prints
text_again = open(file_again) #Not sure if this is working
print (text_again.read()) #Is doing nothing in the Terminal
print("And finally we close the file") #Works
target.close()
At this point I'm wondering why the stuff after "#The default code is done at this point" is not working, I ripped it exactly as-is from another program (Exercise 15 of the same book), my Command line looks like this:
C:\PATH\Study Drills>py SD8.py "test.txt"
We're going to erase 'test.txt'.
If you don't want that, hit CTRL-C (^C)
If you do want that, hit RETURN.
?""
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines
line 1: "Hey"
line 2: "yo"
line 3: "sup"
I'm going to write these to the file.
Type the filename again and I'll read it back to you or press CTRL + C (^C) to exit
>"test.txt"
Now I'll read the file back to you!
BONUS QUESTION: In the point where I say ("#look into error unexpected EOF while parsing, I had to type "", if I don't program ends here") why do I have to put quotation marks? If I don't the program ends with the error message mentioned in the comment.
Once you're done with all your write calls, close() the file. Due to things like OS buffering, the data is not guaranteed to be actually written to the file until you close the file object (which is done automatically when you exit the program, as you might have noticed -- kill your program and the data will be in the file).
In addition, your truncate call is unnecessary -- opening a file in "w" mode immediately truncates it.
I'm having trouble in getting the following code to run, (it's exercise 15 from Zed Shaw's "Learn Python the hard way"):
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r." % filename print txt.read()
print "Type the filename again: " file_again = raw_input("==>")
txt_again = open(file_again)
print txt_again.read()
txt.close() txt_again.close()
I try to run it from the terminal and get the following:
dominics-macbook-4:MyPython Dom$ python ex15_sample.txt
File "ex15_sample.txt", line 1
This is stuff I typed into a file.
^
SyntaxError: invalid syntax
Here's the contents of ex15_sample.txt:
"This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here."
I'm banging my head off the wall! (Python 2.6.1, OS X 10.6.8)
python ex15_sample.txt
Why are you telling Python to run a text file? Don't you mean something more like
python ex15_sample.py ex15_sample.txt
or whatever you've called your Python program?
I am trying to use Pastebin to host two text files for me to allow any copy of my script to update itself through the internet. My code is working, but the resultant .py file has a blank line added between each line. Here is my script...
import os, inspect, urllib2
runningVersion = "1.00.0v"
versionUrl = "http://pastebin.com/raw.php?i=3JqJtUiX"
codeUrl = "http://pastebin.com/raw.php?i=GWqAQ0Xj"
scriptFilePath = (os.path.abspath(inspect.getfile(inspect.currentframe()))).replace("\\", "/")
def checkUpdate(silent=1):
# silently attempt to update the script file by default, post messages if silent==0
# never update if "No_Update.txt" exists in the same folder
if os.path.exists(os.path.dirname(scriptFilePath)+"/No_Update.txt"):
return
try:
versionData = urllib2.urlopen(versionUrl)
except urllib2.URLError:
if silent==0:
print "Connection failed"
return
currentVersion = versionData.read()
if runningVersion!=currentVersion:
if silent==0:
print "There has been an update.\nWould you like to download it?"
try:
codeData = urllib2.urlopen(codeUrl)
except urllib2.URLError:
if silent==0:
print "Connection failed"
return
currentCode = codeData.read()
with open(scriptFilePath.replace(".py","_UPDATED.py"), mode="w") as scriptFile:
scriptFile.write(currentCode)
if silent==0:
print "Your program has been updated.\nChanges will take effect after you restart"
elif silent==0:
print "Your program is up to date"
checkUpdate()
I stripped the GUI (wxpython) and set the script to update another file instead of the actual running one. The "No_Update" bit is for convenience while working.
I noticed that opening the resultant file with Notepad does not show the skipped lines, opening with Wordpad gives a jumbled mess, and opening with Idle shows the skipped lines. Based on that, this seems to be a formatting problem even though the "raw" Pastebin file does not appear to have any formatting.
EDIT: I could just strip all blank lines or leave it as is without any problems, (that I've noticed) but that would greatly reduce readability.
Try adding the binary qualifier in your open():
with open(scriptFilePath.replace(".py","_UPDATED.py"), mode="wb") as scriptFile:
I notice that your file on pastebin is in DOS format, so it has \r\n in it. When you call scriptFile.write(), it translates \r\n to \r\r\n, which is terribly confusing.
Specifying "b" in the open() will cause scriptfile to skip that translate and write the file is DOS format.
In the alternative, you could ensure that the pastebin file has only \n in it, and use mode="w" in your script.
I have a simple bash command here for a script that I am re-writing in Python, and I've done a lot of searching and haven't found a simple answer. I am trying to echo the output of Print to a file, making sure there are no line breaks and that I can pass a variable into it. Here is just a little snippet (there are a lot of lines like this):
echo " ServerName www.${hostName}" >> $prjFile
Now I know it would end up looking something like:
print ("ServerName www.", hostName) >> prjFile
Right? But that doesn't work. Mind you, this is in Python 2.6 (as the machine this script will run on is using that version and there are other dependencies reliant on sticking with that version).
The syntax is;
print >>myfile, "ServerName www.", hostName,
where myfile is a file object opened in mode "a" (for "append").
The trailing comma prevents line breaks.
You might also want to use sys.stdout.softspace = False to prevent the spaces that Python adds between comma-separate arguments to print, and/or to print things as a single string:
print >>myfile, "ServerName www.%s" % hostName,
You can try a simple:
myFile = open('/tmp/result.file', 'w') # or 'a' to add text instead of truncate
myFile.write('whatever')
myFile.close()
In your case:
myFile = open(prjFile, 'a') # 'a' because you want to add to the existing file
myFile.write('ServerName www.{hostname}'.format(hostname=hostname))
myFile.close()
Here is the code from the exercise:
from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
Now I am running Windows 7 and I am running the CMD line with the code
python ex14.py myname
I get this error:
File "ex14.py", line 3
Python ex14.py, user_name
SyntaxError: invalid syntax
There is nothing wrong with the script among visible characters.
check there is no Unicode whitespace in the source e.g., NO-BREAK SPACE character. Create a new script in the same directory:
with open('ex14.py', 'rb') as file:
s = file.read()
print(repr(s)[:60])
u = s.decode('ascii') # this line should raise an error
# if there are bytes outside ascii
check Python version to make sure it is 2.7 (to interpret correctly error messages):
$ python -V
check that the file is not saved using utf-16/32 encodings (#abarnert's suggestion in the comments).
You should see many zero bytes '\x00' in the repr() results in this case.
install python2 and in terminal type
python2 ex14.py myname
will solve the problem
you are running the script in the latest python version
and the syntax of your code is for python version 2
that's why you are getting the syntax error