If I try executing the following code
f = file('test','rb')
fout = file('test.out','wb')
for i in range(10):
a = f.read(1)
fout.write(a)
f.close()
f = fout
f.seek(4)
print f.read(4)
Where 'test' is any arbitrary file, I get:
Traceback (most recent call last):
File "testbad.py", line 12, in <module>
print f.read(4)
IOError: [Errno 9] Bad file descriptor
If however, I change just the fout line to use a temporary file:
import tempfile
f = file('test','rb')
fout = tempfile.NamedTemporaryFile()
for i in range(10):
a = f.read(1)
fout.write(a)
f.close()
f = fout
f.seek(4)
print f.read(4)
There are no errors. Does anyone know why this is? I would have expected the first case to work, but I must be doing something wrong.
Thanks in advance for any help!
you've only opened the file fout for writing, not reading. To open for both use
fout = file('test.out','r+b')
Related
Hi I have a list of filenames
When reading a file, it comes out with an error
Traceback (most recent call last):
File "test.py", line 229, in <module>
f = open(i, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'directory_home.json'
How can I skip the error and complete the rest of the files?
code
file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
for i in file:
f = open(i, 'r')
data = json.load(f)
for i in data['name']:
print(i)
Something like this. Note that 'pass' goes to next iteration. 'Continue' would repeat iteration (in this case useless). 'Break' would end iteration.
file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
for i in file:
try:
f = open(i, 'r')
data = json.load(f)
for i in data['name']:
print(i)
f.colse()
except FileNotFoundError:
print("File does not exist")
pass
Two options.
Option 1: os.path.isfile
import os
file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
for i in file:
if os.path.isfile(file):
f = open(i)
data = json.load(f)
for i in data['name']:
print(i)
else:
continue # or whatever you want to do.
Option 2: Exception handling
file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
for i in file:
try:
f = open(i, 'r')
except FileNotFoundError:
continue # or whatever
data = json.load(f)
for i in data['name']:
print(i)
You should pur your code in a try-except statement, like this
try:
file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
for i in file:
f = open(i, 'r')
data = json.load(f)
for i in data['name']:
print(i)
except FileNotFoundError as e:
# log exception and do whatever you want
pass
In this way, if your code raises an exception because the file si not present, you are able ti handle It.
Please remember that in the code above, just the exception due to a not existing file si catch. This means that if another exception occurs the code will raise a traceback
I have the input file that looks like this (infile.txt):
a x
b y
c z
I want to implement a program that enable user to write to STDOUT or file depending on the command:
python mycode.py infile.txt outfile.txt
Will write to file.
And with this
python mycode.py infile.txt #2nd case
Will write to STDOUT.
I'm stuck with this code:
import sys
import csv
nof_args = len(sys.argv)
infile = sys.argv[1]
print nof_args
outfile = ''
if nof_args == 3:
outfile = sys.argv[2]
# for some reason infile is so large
# so we can't save it to data structure (e.g. list) for further processing
with open(infile, 'rU') as tsvfile:
tabreader = csv.reader(tsvfile, delimiter=' ')
with open(outfile, 'w') as file:
for line in tabreader:
outline = "__".join(line)
# and more processing
if nof_args == 3:
file.write(outline + "\n")
else:
print outline
file.close()
When using 2nd case it produces
Traceback (most recent call last):
File "test.py", line 18, in <module>
with open(outfile, 'w') as file:
IOError: [Errno 2] No such file or directory: ''
What's the better way to implement it?
You can try this:
import sys
if write_to_file:
out = open(file_name, 'w')
else:
out = sys.stdout
# or a one-liner:
# out = open(file_name, 'w') if write_to_file else sys.stdout
for stuff in data:
out.write(stuff)
out.flush() # cannot close stdout
# Python deals with open files automatically
You can also use this instead of out.flush():
try:
out.close()
except AttributeError:
pass
This looks a bit ugly to me, so, flush will be just well.
i'm attempting to read a plain text file and resolve each IP address and (for now) just spit them back out on-screen.
import socket
f = open("test.txt")
num_line = sum(1 for line in f)
f.close()
with open("test.txt", "r") as ins:
array = []
for line in ins:
array.append(line)
for i in range(0,num_line):
x = array[i]
print x
data = socket.gethostbyname_ex(x)
print data
Currently I'm getting the following:
me#v:/home/# python resolve-list2.py
test.com
Traceback (most recent call last):
File "resolve-list2.py", line 15, in <module>
data = socket.gethostbyname_ex(x)
socket.gaierror: [Errno -2] Name or service not known
Googling that error doesn't seem to help me...
The text file only contains one line at the moment (test.com) but i get the same error even with multiple lines/different hosts.
Any suggestions?
Thanks!
import socket
with open("test.txt", "r") as ins:
for line in ins:
print socket.gethostbyname(line.strip())
The goal was to import the infile, read it, and print only two lines into the outfile.This is the code I had in IDLE:
def main():
infile = open('names.py', "r")
outfile = open('orgnames.py', "w")
for i in range (2):
line = ("names.py".readlines())
print (line[:-1], infile = outfile)
infile.close()
outfile.close()
main()
This is the error message I keep getting:
Traceback (most recent call last):
File "C:/Python33/studentnames6.py", line 11, in <module>
main()
File "C:/Python33/studentnames6.py", line 6, in main
line = ("names.py".readlines())
AttributeError: 'str' object has no attribute 'readlines'
I have used the function readlines in a similar situation before and it had worked fine. I don't understand why it's having an error now, or how to fix it.
The error is because names.py is a string, and not a file object. The following code should work for you:
def main():
infile = open('names.py', "r")
outfile = open('orgnames.py', "w")
# Prints the first two lines in outfile
for line in infile.readlines()[:2]:
outfile.write(line)
infile.close()
outfile.close()
main()
Ok well i have another question. I implemented the error checking but for some reason it still isn't working. I still get a python error instead of the error i just wrote in the program.
Traceback (most recent call last):
File "E:/python/copyfile.py", line 31, in <module>
copyFile()
File "E:/python/copyfile.py", line 8, in copyFile
file1 = open(source,"r")
IOError: [Errno 2] No such file or directory: 'C:/Users/Public/asdf.txt'
check out the shutil module in standard library:
shutil.copyfile(src, dst)
http://docs.python.org/2/library/shutil.html#shutil.copyfile
I would rather ask you to write your own:
import os
import hashlib
def md5ChkSum(_file): # Calculates MD5 CheckSum
with open(_file, 'rb') as fp:
hash_obj = hashlib.md5()
line = fp.readline()
while line:
hash_obj.update(line)
line = fp.readline()
return hash_obj.hexdigest()
def copier(_src, _dst):
if not os.path.exists(_src):
return False
_src_fp = open(_src, "r")
_dst_fp = open(_dst, "w")
line = _src_fp.readline()
while line:
_dst_fp.write(line)
line = _src_fp.readline()
_src_fp.close()
_dst_fp.close()
if md5ChkSum(_src) == md5ChkSum(_dst):
return "Copy: SUCCESSFUL"
return "Copy: FAILED"
res = copier(r"/home/cnsiva/6.jpg", r"/home/cnsiva/6_copied.jpg")
if not res:
print "FILE Does not Exists !!!"
else: print res
OUTPUT:
Copy: SUCCESSFUL