File creation function in Python - python

Does open() in python create a file? If not, is there a function that does that? When I use this, it gives me
"IOError: [Errno 2] No such file or directory:
'/home/sanjiv/Desktop/COSURP/pyfiles/f1.txt'"
Was I not supposed to put the location to create the file? If not, where does it create it
f = open('/home/sanjiv/Desktop/COSURP/pyfiles/f1.txt', 'r+')
gpa = {'fall15':4.0, 'spr16':3.47, 'fall16':4.0}
for s in gpa:
f.write(str(s) + '\n')
f.close()

If you want to open the file for writing you should use the w as the second parameter (of the open function), and not r+.
The w will open the file for writing (and truncating the file if it already exists):
f = open('/home/sanjiv/Desktop/COSURP/pyfiles/f1.txt', 'w')
gpa = {'fall15':4.0, 'spr16':3.47, 'fall16':4.0}
for s in gpa:
f.write(str(s) + '\n')
f.close()
Note that if you want to open a file in the directory /home/sanjiv/Desktop/COSURP/pyfiles/ this directory must exists and you must have write-permissions to this directory.

Related

No such file or directory: 'results.txt' [duplicate]

This question already has answers here:
open() in Python does not create a file if it doesn't exist
(17 answers)
Closed 2 years ago.
I'm trying to write to a txt file but faced the following error message: [Errno 2] No such file or directory: 'results.txt'. The results.csv file contains data separated by pipeline delimiters. May I know what went wrong and how do I solve this?
results_path = "results.csv"
dest_path = "results.txt"
def row_count(results_path):
return len(open(results_path).readlines())
def add_header_footer(results_path, dest_path, file_name, date_today):
with open(results_path) as from_file, open(dest_path) as to_file:
header = 'H|ABC|' + file_name + '|' + date_today + '\n'
footer = 'E|' + str(row_count(results_path)) + '|\n'
to_file.write(header)
shutil.copyfileobj(from_file, to_file)
to_file.write(footer)
add_header_footer(results_path, dest_path, 'Results_Today', '20190818')
You should use open destination file with the w+ mode. It tries to write to the file and if it does not exist then it creates the file. Change this part of your code and see whether it works.
open(dest_path, 'w+') as to_file
There are other modes too like, a+ for appending. Read more here
Python can find your file result_path.
Try to set your results_path variable as an Absolute path.
Normally that Error message is shown when you call a file which is not in the same level as your py file.
Hope this is helpful! :D

Trying to replace original file with created temp file

I want to do some changes in one file. For this purpose I am doing a temporary file where I write content with all wanted changes and at the end I try to replace the original file with this temp one.
Temp file is created and it looks like I expected, but replacing operation do not work.
This is my code which fails:
with tempfile.NamedTemporaryFile(mode='w', prefix=basename, dir=dirname, delete=False) as temp, open(file_path, 'r') as f:
for line in f:
temp.write(line + " test")
os.replace(temp.name, file_path)
but this gives me an error:
PermissionError: [WinError 32] The process cannot access the file
because it is being used by another process
Is my usage of 'replace' function is wrong?
your command os.replace(temp.name, file_path) has to be out of the with.
with tempfile.NamedTemporaryFile(mode='w', prefix=basename, dir=dirname, delete=False) as temp, open(file_path, 'r') as f:
for line in f:
temp.write(line + " test")
os.replace(temp.name, file_path)
When you are calling replace() inside 'with' the file is still open as you are still inside the scope of 'with'.
As soon as you're out of 'with' the file has now been closed and you can now replace with os.replace().
Try it.
with tempfile.NamedTemporaryFile(mode='w', prefix=basename, dir=dirname, delete=False) as temp, open(file_path, 'r') as f:
for line in f:
temp.write(line + " test")
os.replace(temp.name, file_path)

Close already open csv in Python

Is there a way for Python to close that the file is already open file.
Or at the very least display a popup that file is open or a custom written error message popup for permission error.
As to avoid:
PermissionError: [Errno 13] Permission denied: 'C:\\zf.csv'
I've seen a lot of solutions that open a file then close it through python. But in my case. Lets say I left my csv open and then tried to run the job.
How can I make it so it closes the currently opened csv?
I've tried the below variations but none seem to work as they expect that I have already opened the csv at an earlier point through python. I suspect I'm over complicating this.
f = 'C:\\zf.csv'
file.close()
AttributeError: 'str' object has no attribute 'close'
This gives an error as there is no reference to opening of file but simply strings.
Or even..
theFile = open(f)
file_content = theFile.read()
# do whatever you need to do
theFile.close()
As well as:
fileobj=open('C:\\zf.csv',"wb+")
if not fileobj.closed:
print("file is already opened")
How do I close an already open csv?
The only workaround I can think of would be to add a messagebox, though I can't seem to get it to detect the file.
filename = "C:\\zf.csv"
if not os.access(filename, os.W_OK):
print("Write access not permitted on %s" % filename)
messagebox.showinfo("Title", "Close your CSV")
Try using a with context, which will manage the close (__exit__) operation smoothly at the end of the context:
with open(...) as theFile:
file_content = theFile.read()
You can also try to copy the file to a temporary file, and open/close/remove it at will. It requires that you have read access to the original, though.
In this example I have a file "test.txt" that is write-only (chmod 444) and it throws a "Permission denied" error if I try writing to it directly. I copy it to a temporary file that has "777" rights so that I can do what I want with it:
import tempfile, shutil, os
def create_temporary_copy(path):
temp_dir = tempfile.gettempdir()
temp_path = os.path.join(temp_dir, 'temp_file_name')
os.chmod(temp_path, 0o777); # give full access to the tempfile so we can copy
shutil.copy2(path, temp_path) # copy the original into the temp one
os.chmod(temp_path, 0o777); # replace permissions from the original file
return temp_path
path = "./test.txt" # original file
copy_path = create_temporary_copy(path) # temp copy
with open(copy_path, "w") as g: # can do what I want with it
g.write("TEST\n")
f = open("C:/Users/amol/Downloads/result.csv", "r")
print(f.readlines()) #just to check file is open
f.close()
# here you can add above print statement to check if file is closed or not. I am using python 3.5

How do I open a file, passed to open as a variable?

def readfile(file):
edges = [] # to contain tuples of all edges
with open(file) as f:
for line in f:
I'm trying to pass in a text file called file, then read it, but it doesn't work. Even if I cast file to a string it doesn't work.
Python says
with open(file) as f: IOError: [Errno 22] invalid mode ('r') or
filename: "<type 'file'>"
How do I open a file, passed to open as a variable?
Rename file by filename as file is a built-in name for python :
def readfile(filename):
edges = [] # to contain tuples of all edges
with open(filename) as f:
for line in f:
open() use 'r' as default mode.
First of all , as file is a type in python you shouldn't use it as a variable name or file name , second you need to put the file name in quote inside the open function and note that open function use read mod as default ! :
with open('file_name.txt','r') as f:
for line in f:

Creating new text file in Python?

Is there a method of creating a text file without opening a text file in "w" or "a" mode? For instance If I wanted to open a file in "r" mode but the file does not exist then when I catch IOError I want a new file to be created
e.g.:
while flag == True:
try:
# opening src in a+ mode will allow me to read and append to file
with open("Class {0} data.txt".format(classNo),"r") as src:
# list containing all data from file, one line is one item in list
data = src.readlines()
for ind,line in enumerate(data):
if surname.lower() and firstName.lower() in line.lower():
# overwrite the relevant item in data with the updated score
data[ind] = "{0} {1}\n".format(line.rstrip(),score)
rewrite = True
else:
with open("Class {0} data.txt".format(classNo),"a") as src:
src.write("{0},{1} : {2}{3} ".format(surname, firstName, score,"\n"))
if rewrite == True:
# reopen src in write mode and overwrite all the records with the items in data
with open("Class {} data.txt".format(classNo),"w") as src:
src.writelines(data)
flag = False
except IOError:
print("New data file created")
# Here I want a new file to be created and assigned to the variable src so when the
# while loop iterates for the second time the file should successfully open
At the beginning just check if the file exists and create it if it doesn't:
filename = "Class {0} data.txt"
if not os.path.isfile(filename):
open(filename, 'w').close()
From this point on you can assume the file exists, this will greatly simplify your code.
No operating system will allow you to create a file without actually writing to it. You can encapsulate this in a library so that the creation is not visible, but it is impossible to avoid writing to the file system if you really want to modify the file system.
Here is a quick and dirty open replacement which does what you propose.
def open_for_reading_create_if_missing(filename):
try:
handle = open(filename, 'r')
except IOError:
with open(filename, 'w') as f:
pass
handle = open(filename, 'r')
return handle
Better would be to create the file if it doesn't exist, e.g. Something like:
import sys, os
def ensure_file_exists(file_name):
""" Make sure that I file with the given name exists """
(the_dir, fname) = os.path.split(file_name)
if not os.path.exists(the_dir):
sys.mkdirs(the_dir) # This may give an exception if the directory cannot be made.
if not os.path.exists(file_name):
open(file_name, 'w').close()
You could even have a safe_open function that did something similar prior to opening for read and returning the file handle.
The sample code provided in the question is not very clear, specially because it invokes multiple variables that are not defined anywhere. But based on it here is my suggestion. You can create a function similar to touch + file open, but which will be platform agnostic.
def touch_open( filename):
try:
connect = open( filename, "r")
except IOError:
connect = open( filename, "a")
connect.close()
connect = open( filename, "r")
return connect
This function will open the file for you if it exists. If the file doesn't exist it will create a blank file with the same name and the open it. An additional bonus functionality with respect to import os; os.system('touch test.txt') is that it does not create a child process in the shell making it faster.
Since it doesn't use the with open(filename) as src syntax you should either remember to close the connection at the end with connection = touch_open( filename); connection.close() or preferably you could open it in a for loop. Example:
file2open = "test.txt"
for i, row in enumerate( touch_open( file2open)):
print i, row, # print the line number and content
This option should be preferred to data = src.readlines() followed by enumerate( data), found in your code, because it avoids looping twice through the file.

Categories