|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
SlickEdit: Code in over 40 languages across 7 platforms. SlickEdit’s unmatched power, speed, and flexibility allows even the most accomplished developers to write better code faster. Download a free trial today! |
|
#1
|
|||
|
|||
|
Working with files
I'm not sure why this doesn't work. It's pretty simple... just tests if it can read/write the file.
Code:
#! /usr/bin/env python
import sys
class FileCheck:
def check(self, filename):
try:
fp = open("filename", "r")
print "Can read from " + filename
fp.close()
except:
print "Cannot read from " + filename
try:
fp = open("filename", "w")
print "Can write from " + filename
fp.close()
except:
print "Cannot read from " + filename
def main():
file = FileCheck()
if len(sys.argv) != 2:
print "Usage: ./filecheck <path/filename>"
else:
file.check(sys.argv[1])
if __name__ == "__main__":
main()
|
|
#2
|
||||
|
||||
|
What error do you get ? Your script worked when I tried it (under Win XP though).
|
|
#3
|
|||
|
|||
|
When I give it a filename that doesn't exist it still says it can read/write. When I type "fp =open("oiwjedoiwjed", "r") directly into the interpreter, I get an exception. But in my program the except: stuff doesn't run...
|
|
#4
|
||||
|
||||
|
Could have somthing to do with the filename you passing to your files. instead of using the variable 'filename' your passing in a string "filename"
![]() Quote:
Code:
#!/usr/bin/env python def check(path): """ Check a path to see if the file is readable/writable or not. """ try: print 'Can read from', file(path, 'r') except IOError: print 'Cannot read from', path try: print 'Can write to', file(path, 'w') except IOError: print 'Cannot write to', path if __name__ == "__main__": import sys if len(sys.argv) != 2: print 'Usage: ./filecheck <path/filename>' else: check(sys.argv[1]) changed things around and it worked fine.. oh you really dont need a class there; people seems to use classes where a function would be fine, so not just you.Mark. |
|
#5
|
|||
|
|||
|
Thanks alot
|
|
#6
|
||||
|
||||
|
No problem happy to help!
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Working with files |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|