zed shaw's exercise 15 open function - python

I am a little stuck with zed shaw's exercise 15.
Actually I had no problem with the original program,
but the problem is when I try out the extra credit
where he asks us to use raw input instead of argv.
so, this is the code I used
filename=raw_input("enter filename :")
print "here's your file %r" % filename
txt=open(filename)
print txt.read()
when it asks for filename, I give the path e:\python\ex15_sample.txt
I am getting the following error in
this line --> txt = open(filename)
and it further says
no such file or directory
So, what do I do?

Your code is just fine. You made an error when entering the filename. Check that the file really exists.
>>> filename=raw_input('enter filename :')
enter filename :c:\Users\All Users\Autodesk\Revit\Addins\2012\RevitLookup.addin
>>> txt = open(filename)
>>> print txt.read()
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<RevitAddIns>
<AddIn Type="Application">
<Assembly>C:\Program Files (x86)\Revit 2012 SDK\RevitLookup\CS\bin\Debug\RevitLookup.dll</Assembly>
<ClientId>356CDA5A-E6C5-4c2f-A9EF-B3222116B8C8</ClientId>
<FullClassName>RevitLookup.App</FullClassName>
<Name>Revit Lookup</Name>
<VendorId>ADSK</VendorId>
<VendorDescription>Autodesk, www.autodesk.com</VendorDescription>
</AddIn>
</RevitAddIns>
(uh, that's just some file I happen to have lying around on my pc...)
Be sure to NOT use quotation marks when entering the file - or strip them of afterwards! Doing this for argv might work, but definitly not for raw_input.
EDIT: I think that's the problem: You are entering the filename with quotation marks (such as you get when you do shift-right-click "Copy As Path" in explorer). For sys.argv, these are removed by (Python? OS? I think Python...), but not with raw_input.

Due to the fact that you are using Windows you could try have to use either a / (forward slash) when entering a filename or use a double backslash for the path-seperator \\.
To enter your filename you could then try e:/python/ex15_sample.txt or e:\\python\\ex15_sample.txt.

I used the following program to finally get it work:
print "Type your filename:"
filename = raw_input(">")
txt = open(filename)
print txt.read()
I kind of puzzled why the OP used %r formatter. I didn't use it and my program still work. Is there something I'm missing? Thanks.

Related

Python script not writing to txt file

I have a Python script that runs properly on my laptop, but when running on my raspberry pi, the following code does not seem to be working properly. Specifically, "TextFile.txt" is not being updated and/or saved.
openfile = open('/PATH/TextFile.txt','w')
for line in lines:
if line.startswith(start):
openfile.write(keep+'\n')
print ("test 1")
else:
openfile.write(line)
print ("test 2")
openfile.close()
I am seeing "test 1" and "test 2" in my output, so I know that the code is being reached, paths are correct, etc
It may be due to a permissions problem. I am running the script from the terminal by using:
usr/bin/python PATH/script.py
Python is owned by "root" and script.py is owned by "Michael".
My first guess:
Does the file exist? If it does not exist then you cannot write to it. Try this to create the file if it does not exist: file = open('myfile.dat', 'w+')
Additionally manually opening and closing file handles is bad practice in python. The with statement handles the opening and closing of the resource automatically for you:
with open("myfile.dat", "w+") as f:
#doyourcalculations with the file object here
for line in f:
print line
All, thank you for your input. I was able to figure out that it was writing to the new file, but it was overwriting with the same text. The reason was because ".startswith" was returning false when I expected true. The misconception was due to the difference between how Windows and Unix treat new line characters (/n /r).
Since your code is running, there should be a file somewhere.
You call "PATH/script.py", but there is "/PATH/TextFile.txt" in your program. Is the slash before PATH a mistake? Have you checked the path in your program is really where you are looking for the output file?

use Python to open a file in read mode

I am trying to open a file in read mode using Python. The error I am receiving suggest I am using the won filename or read mode. When I type the file path into my computer, it works. I tried to assign the input filename to a variable and then opening the variable in read mode. I also tried typing in the full path and opening the path in read mode. Both game me an error.
Code:
workingDirec = raw_input("What is the working directory?")
original_file = raw_input("The input filename is?")
def calculateZscore():
"Z score calc"
full_original = os.path.join(workingDirec,original_file)
print full_original
f = open ('C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt','r')
print f
My results:
Using full path output:
What is the working directory?C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data
The input filename is?NCSIDS_ObsExp.txt
C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt'
Using variable output:
IOError: [Errno 2] No such file or directory: 'full_original'
On Windows your paths must be escaped because Windows uses backslashes \ to denote path separators.
Backslashes however are typically used as escape sequences and are used in Python as such as well! So you have to "escape" them like this:
f = open ('C:\\Users\\tpmorris\\ProgramingAndScripting\\Trial 2 Data\\Trial 2 Data\\NCSIDS_ObsExp.txt','r')
See:
Windows path in Python
Using Python on Windows
Firstly , on Windows, you must escape backslashes (double backslash) if you are going to use Windows path syntax, for the reasons pointed out by #James Mills answer.
Another option is to use forward slashes; Python will interpret these correctly in os.path.
You could use as your command line path input:
C:/Users/tpmorris/ProgramingAndScripting/Trial 2 Data/Trial 2 Data
Or add
/NCSIDS_ObsExp.txt
to the above if you were going to use a hardcoded path.
Also you should make some small changes to your code if you want to print the contents of your text file:
First, your file open should be done using a with statement. This will ensure the file object's built in __enter__ and __exit__ methods get called, in particular, if you forget to close the file when you are done after you've opened it.
See Understanding Python's with statement for more.
Second, if you want to print each line in your text file, don't try to print the file object. Rather loop through the lines and print them.
So your code for accepting command line input should be:
import os
workingDirec = raw_input("What is the working directory?")
original_file = raw_input("The input filename is?")
full_original = os.path.join(workingDirec,original_file)
print full_original
with open(full_original,'r') as f:
for line in f:
print line
f.close()
I removed the def of a function to do something else in the midst of your file read code. That def should go elsewhere.

File in and file out in python

i had created a python program but it was not working. this program would take in the input for a file and then display the file contents . the only error i was getting is a syntax error well i could not find the error . Please help me .
the code was :-
nm = input(“enter file name “)
str = raw_input(“enter ur text here: \n”)
f = open(nm,”w”)
f.write(str)
f.close()
print “1.See the file\n”
print “2.Exit\n”
s = input(“enter ur choice “)
if s == 1 :
fi = open(nm,”r”)
cont = fi.read()
for i in cont:
print i
else :
print “thank you “
The problem is that you are reading the filename using input() instead of raw_input(). See this answer that explains:
If you use input, then the data you type is is interpreted as a Python
Expression which means that you end up with gawd knows what type of
object in your target variable, and a heck of a wide range of
exceptions that can be generated. So you should NOT use input unless
you're putting something in for temporary testing, to be used only by
someone who knows a bit about Python expressions.
raw_input always returns a string because, heck, that's what you
always type in ... but then you can easily convert it to the specific
type you want, and catch the specific exceptions that may occur.
Hopefully with that explanation, it's a no-brainer to know which you
should use.
Also, since you are reading in the file contents by using fi.read(), your for loop for i in cont: will select each character of the file's contents one at a time, instead of each line. Something to be aware of!

Python - writing lines from file into IRC buffer

Ok, so I am trying to write a Python script for XCHAT that will allow me to type "/hookcommand filename" and then will print that file line by line into my irc buffer.
EDIT: Here is what I have now
__module_name__ = "scroll.py"
__module_version__ = "1.0"
__module_description__ = "script to scroll contents of txt file on irc"
import xchat, random, os, glob, string
def gg(ascii):
ascii = glob.glob("F:\irc\as\*.txt")
for textfile in ascii:
f = open(textfile, 'r')
def gg_cb(word, word_eol, userdata):
ascii = gg(word[0])
xchat.command("msg %s %s"%(xchat.get_info('channel'), ascii))
return xchat.EAT_ALL
xchat.hook_command("gg", gg_cb, help="/gg filename to use")
Well, your first problem is that you're referring to a variable ascii before you define it:
ascii = gg(ascii)
Try making that:
ascii = gg(word[0])
Next, you're opening each file returned by glob... only to do absolutely nothing with them. I'm not going to give you the code for this: please try to work out what it's doing or not doing for yourself. One tip: the xchat interface is an extra complication. Try to get it working in plain Python first, then connect it to xchat.
There may well be other problems - I don't know the xchat api.
When you say "not working", try to specify exactly how it's not working. Is there an error message? Does it do the wrong thing? What have you tried?

Learn Python the Hard Way Exercise 17 Extra Question(S)

I'm doing Zed Shaw's fantastic Learn Python The Hard Way, but an extra question has me stumped: Line 9--10 could be written in one line, how? I've tried some different thoughts, but to no avail. I could move on, but what would the fun in that be?
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 too, how?
input = open(from_file)
indata = input.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()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
Zed also writes that he could do the whole script in one line. I'm not exactly sure what he means by that.
Feel free to help me however you want: by giving the answer or merely hinting---and perhaps including a collapsed or hidden answer to the question.
indata = open(from_file).read()
shutil is the way to do one-liner file copies in Python:
shutil.copy(sys.argv[1], sys.argv[2])
Putting the import shutil, sys on the same line as this one (with a semicolon in-between, of course) would however be stylistically goofy;-).
Well you can just do "algebraic substitution," right? ...assuming you don't care about the "UI"...
open(to_file, 'w').write(open(from_file).read())
from sys import argv
open(argv[2], 'w').write(open(argv[1]).read())
I agree with the algebraic substitution mentioned by #dash-tom-bang.
My functioning Exercise 17 extra credit has 5 lines. The operation is being conducted on one line.
open(to_file, 'w').write(open(from_file).read())
followed by a simple 'print' for verification feedback
print "File %s copied to %s" % (from_file, to_file)
I should have a 6th line that replaces the original ''output.close'' but I am confused about how to do this without the ''output'' variable? Ahh, since I now have no output variable there is nothing to close.
btw- It is a little spooky for me to see the same exact line typed here that I have worked out and entered myself in gedit. Great stuff, I am really enjoying the mental challenge and community support.
Edit:answered my own question
try the following code:
import shutil, sys; shutil.copy(sys.argv[0], sys.argv[2])
output = open(to_file, 'w')
output.write(indata)
can be written as
open(to_file, 'w').write(indata)
Had some fun with this one. In answering this I was looking for a solution that preserved the functionality, used the file commands the exercise was about and did not use ";" to combine lines. Closest I could come is
open(input("Out?: "), 'w').write(open(input("In?: ")).read())
Not quite the same functionality as it prompts for input rather than taking command line. But a single line that gets the job done while using the file commands in the exercise and avoiding concatenating lines using semi colon.
He answers this below in the section "Common Student Questions":
No way you can make this one line!
That ; depends ; on ; how ; you ; define ; one ; line ; of ; code.
Hey Kiwi (and whomever else finds this!),
I'm on the same exercise and I believe I've cracked it.
There are two possible readings of Shaw's "I could make this one line long" tease.
He could make the Python script one line long, upon importing all the necessary commands from the modules, e.g from sys import argv, etc.
He could copy the contents of one file to another in one line using the command line.
I personally think he means the latter, but I will explain both solutions for the sake of learning!
The first (Long) solution:
You must acknowledge that you require the importx from y lines in the Python file, otherwise argv and exist won't work because they will only have been implicitly referenced, i.e. you haven't made it clear to Python that you want to use these functions.
The next thing to do is delete all irrelevant code, with irrelevant being code that is written for the benefit of the user, i.e. print, raw_input(), len(), etc.
If you do this, you will be left with:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
indata = open(from_file).read()
out_file = open(to_file, 'w')
out_file.write(indata)
out_file.close()
in_file.close()
To make this even shorter, you can begin nesting the variables and function in one another. This is the same principle as in maths when you could define a function and then substitute the variable representing that function into another function.
For example:
y = x + 3
z = y, which is essentially z = (x + 3)
If you work this through, you can simplify the code down to:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
(open(to_file, 'w').write(open(from_file).read()))
You can then use lots of ; to link up all the lines of code and vio-la you're done.
Note: You don't need to close the files, as you did in the original, as Python will automatically close them upon executing the script.
The second (Short) solution:
If you look at his 'What You Should See' section, he uses cat in the terminal. This is short for concatenation, which is a means of connecting strings together. If you combine it with > you can overwrite the contents of one file with another in one line:
cat from_file.txt > to_file.txt
That's it. One line that will take the contents of one file and put it into another.
Of course, both solutions aren't perfect, as the first isn't truly one line and the second doesn't even use Python!
Feedback appreciated, I only started doing this two days ago...
Cutting away everything you don't need, all the 'features you don't need' as Zed puts it, and you get one line. It's even less than 80 characters in length, can't get much more 'pythonic' than that!
from sys import argv; s, f, t = argv; (open(t, 'w').write(open(f).read()))
All he is saying is that you can use a semicolon to put two lines onto one line and have it run
in_file = open(from_file); indata = in_file.read()
You could do that with the whole piece of code if you wanted to
I'm also doing the same book online. I tried this, and it worked:
open(to_file, 'w').write(open(from_file).read())
In other words, I opened the file I was copying to in the write mode and then inserted the contents of the file I was copying from, after opening and reading it, into the write function. I checked my files and it worked. Yay!
The below line worked for me:
open(to_file, 'w').write(open(from_file).read())
There was a hint within the Common Student Questions section:
"No way you can make this one line!
That ; depends ; on ; how ; you ; defi ne ; one ; line ; of ; code."
Note: This is clearly not best practice and difficult to read.
from sys import argv
script, from_file, to_file = argv
in_file = open(from_file); indata = in_file.read(); out_file = open(to_file, 'w'); out_file.write(indata); out_file.close(); in_file.close()
This the most reduced code that preserves the ui maybe there is other better solutions.
From 21 lines down to 8 lines of code.
Before:
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 too, how?
input = open(from_file)
indata = input.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()
output = open(to_file, 'w')
output.write(indata)
print("Alright, all done.")
To:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
output = open(to_file, 'w').write(open(from_file).read())
print("""Copying from %s to %s\nThe input file is %d bytes long\nDoes the output file exist? %r\nReady, hit RETURN to continue, CTRL-C to abort.\nAlright, all done.""" % (from_file, to_file, len(open(from_file).read()), exists(to_file)))

Categories

Resources