Syntax error in reading text file - python

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?

Related

python copying text from one file to another

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

Unreadable codes while using read() in python

I'm learning python2.7 in Windows 8.1.
I used echo "XXX" to create a new file, and then I used python to read it, but it output unreadable files.
But when I used GUI to type something into a new file then read it in python it works.
Is there anyone could help me please ?
I wrote this in powershell 2.0
PS C:\Users\Fingal> echo "Stack Overflow is such a good site." > test.txt
And then I wrote this in Notepad++, and save it as test.txt in C:\Users\Fingal
from sys import argv
script, file_name = argv
txt = open(file_name)
print txt.read()
txt.close()
Then I back to powershell and type:
PS C:\Users\Fingal\> python test.py test.txt
a ataaacaka a0avaearafalaoawa aiasa asauacaha aaa agaoaoada asaiattaea.aa
It output unreadable code.
Fingal

Python program not printing text file

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.

How to read next logical line in python

I would like to read the next logical line from a file into python, where logical means "according to the syntax of python".
I have written a small command which reads a set of statements from a file, and then prints out what you would get if you typed the statements into a python shell, complete with prompts and return values. Simple enough -- read each line, then eval. Which works just fine, until you hit a multi-line string.
I'm trying to avoid doing my own lexical analysis.
As a simple example, say I have a file containing
2 + 2
I want to print
>>> 2 + 2
4
and if I have a file with
"""Hello
World"""
I want to print
>>>> """Hello
...World"""
'Hello\nWorld'
The first of these is trivial -- read a line, eval, print. But then I need special support for comment lines. And now triple quotes. And so on.
You may want to take a look at the InteractiveInterpreter class from the code module .
The runsource() method shows how to deal with incomplete input.
Okay, so resi had the correct idea. Here is my trivial code which does the job.
#!/usr/bin/python
import sys
import code
class Shell(code.InteractiveConsole):
def write(data):
print(data)
cons = Shell()
file_contents = sys.stdin
prompt = ">>> "
for line in file_contents:
print prompt + line,
if cons.push(line.strip()):
prompt = "... "
else:
prompt = ">>> "

exercise 14 learning python the hard way

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

Categories