Create file in python dynamically - python

I know it's a noob question but I have some difficulties to make it works
def create(file):
f = open(file,'w')
it returns "IOError: [Errno 2] No such file or directory: "
If I do that it works of course:
file ="myfile"
f = open(file,'w')
But I can't figure out how to create my file from the function parameter
Sorry for the noob question, thanks in advance for your help.

when you pass the "http://somesite.com/" as file to your function python treats it as a directory structure.
As soon as python gets to "http:/" it presumes we have a directory. Using forward slashes in unix is not allowed and I imagine it is the same for windows.
To turn the name into something useable you can use some variation of urlparse.urlsplit:
import urlparse
import urlparse
def parse(f):
prse = urlparse.urlsplit(f)
return prse.netloc if f.startswith("http") else prse.path.split("/",1)[0]

Sites can look like paths to directories to the operating system. for instance: stackoverflow.com/something will be interpreted as a directory stackoverflow.com in which there is a file something.
You can see this when you use os.path.dirname:
>>> os.path.dirname('stackoverflow.com/something')
'stackoverflow.com'
If this is indeed the case, and you still want to proceed, you're passing a path to a location in a directory and not just a file name.
You have to make sure the directory stackoverflow.com exists first:
file_path = 'stackoverflow.com/something'
dirname = os.path.dirname(file_path)
if not os.path.exists(dirname):
# if stackoverflow.com directory does not exist it will be created
os.makedirs(dirname)
# .. carry on to open file_path and use it.
Watch out from http:// and the likes and consider using a real url parser.
tip: file is already defined in python, you shouldn't override it by using it to name a variable.

Editing:
def create(file):
f = open(file,'w')
f.close()
If you call this function using:
create('myfile.txt')
It will create a file named myfile.txt in whatever directory the code is being run from. Note that you are passing in a string not an object.
Since I now see you are passing in a string similar to http://www.google.com, you are trying to create a file named www.google.com in the http: folder. You are going to have to truncate or change the / since Windows files cannot contain that character in their names.
We'll use everything after the last / in this example:
def create(filename):
filename = re.sub(r'.*//*', '', filename)
f = open(filename, 'w')
f.close()
So calling: create('www.google.com/morestuff/things') will create a file called things

Related

A way to create files and directories without overwriting

You know how when you download something and the downloads folder contains a file with the same name, instead of overwriting it or throwing an error, the file ends up with a number appended to the end? For example, if I want to download my_file.txt, but it already exists in the target folder, the new file will be named my_file(2).txt. And if I try again, it will be my_file(3).txt.
I was wondering if there is a way in Python 3.x to check that and get a unique name (not necessarily create the file or directory). I'm currently implementing it doing this:
import os
def new_name(name, newseparator='_')
#name can be either a file or directory name
base, extension = os.path.splitext(name)
i = 2
while os.path.exists(name):
name = base + newseparator + str(i) + extension
i += 1
return name
In the example above, running new_file('my_file.txt') would return my_file_2.txt if my_file.txt already exists in the cwd. name can also contain the full or relative path, it will work as well.
I would use PathLib and do something along these lines:
from pathlib import Path
def new_fn(fn, sep='_'):
p=Path(fn)
if p.exists():
if not p.is_file():
raise TypeError
np=p.resolve(strict=True)
parent=str(np.parent)
extens=''.join(np.suffixes) # handle multiple ext such as .tar.gz
base=str(np.name).replace(extens,'')
i=2
nf=parent+base+sep+str(i)+extens
while Path(nf).exists():
i+=1
nf=parent+base+sep+str(i)+extens
return nf
else:
return p.parent.resolve(strict=True) / p
This only handles files as written but the same approach would work with directories (which you added later.) I will leave that as a project for the reader.
Another way of getting a new name would be using the built-in tempfile module:
from pathlib import Path
from tempfile import NamedTemporaryFile
def new_path(path: Path, new_separator='_'):
prefix = str(path.stem) + new_separator
dir = path.parent
suffix = ''.join(path.suffixes)
with NamedTemporaryFile(prefix=prefix, suffix=suffix, delete=False, dir=dir) as f:
return f.name
If you execute this function from within Downloads directory, you will get something like:
>>> new_path(Path('my_file.txt'))
'/home/krassowski/Downloads/my_file_90_lv301.txt'
where the 90_lv301 part was generated internally by the Python's tempfile module.
Note: with the delete=False argument, the function will create (and leave undeleted) an empty file with the new name. If you do not want to have an empty file created that way, just remove the delete=False, however keeping it will prevent anyone else from creating a new file with such name before your next operation (though they could still overwrite it).
Simply put, having delete=False prevents concurrency issues if you (or the end-user) were to run your program twice at the same time.

How to open a specific path with open()?

I'm trying to build a file transfer system with python3 sockets. I have the connection and sending down but my issue right now is that the file being sent has to be in the same directory as the program, and when you receive the file, it just puts the file into the same directory as the program. How can I get a user to input the location of the file to be sent and select the location of the file to be sent to?
I assume you're opening files with:
open("filename","r")
If you do not provide an absolute path, the open function will always default to a relative path. So, if I wanted to open a file such as /mnt/storage/dnd/5th_edition.txt, I would have to use:
open("/mnt/storage/dnd/4p5_edition","r")
And if I wanted to copy this file to /mnt/storage/trash/ I would have to use the absolute path as well:
open("/mnt/storage/trash/4p5_edition","w")
If instead, I decided to use this:
open("mnt/storage/trash/4p5_edition","w")
Then I would get an IOError if there wasn't a directory named mnt with the directories storage/trash in my present folder. If those folders did exist in my present folder, then it would end up in /whatever/the/path/is/to/my/current/directory/mnt/storage/trash/4p5_edition, rather than /mnt/storage/trash/4p5_edition.
since you said that the file will be placed in the same path where the program is, the following code might work
import os
filename = "name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
Its pretty simple just get the path from user
subpath = raw_input("File path = ")
print subpath
file=open(subpath+str(file_name),'w+')
file.write(content)
file.close()
I think thats all you need let me know if you need something else.
like you say, the file should be in the same folder of the project so you have to replace it, or to define a function that return the right file path into your open() function, It's a way that you can use to reduce the time of searching a solution to your problem brother.
It should be something like :
import os
filename = "the_full_path_of_the_fil/name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
then you can use the value of the f variable as a path to the directory of where the file is in.

Change Saving-Path - Python

I´m trying to save a file, which I create with the "open" function.
Well I tried nearly everything to change the directory, but nothing works. The file gets always saved in the folder of my file, which I read in before.
file = open(fname[0] + ft, 'w')
file.write("Test")
file.close()
So this is it simple, but what do I have to add, to change the path of creation?
The File Dialog in a individual Function:
global fname
fname = QFileDialog.getOpenFileName(None, 'Please choose your File.',"C:\\Program Files", "Text-Files(*.txt)")
And the File Typ ( in a individual Function too) I set the file type by ticking a check box and ft will set to .py or .pyw
if self.exec_py.isChecked() == True:
global ft
ft = ".py"
I should have mentioned that I already tried os.path.join and os.chdir, but the file will get printed in the file anyway. Any solutions or approaches how to fix it? Here is how i tried it:
tmppath = "C:/temp"
tmp = os.path.join(tmppath,fname[0]+ft)
file = open(tmp, 'w')
Your question is a little short on details, but I am guessing that fname is the tuple returned by QFileDialog, and so fname[0] is the absolute path of the original file. So if you display fname[0], you will see something like this:
>>> fname[0]
'C:\\myfolder\\file.txt'
Now look what happens when you try to use that with os.path.join:
>>> tmppath = 'C:\\temp'
>>> os.path.join(tmppath, fname[0])
'C:\\myfolder\\file.txt'
Nothing! Conclusion: attempting to join two absolute paths will simply return the original path unchanged. What you need to do instead is take the basename of the original path, and join it to the folder where you want to save it:
>>> basename = os.path.basename(fname[0])
>>> basename
'file.txt'
>>> os.path.join(tmppath, basename)
'C:\\tmp\\file.txt'
Now you can use this new path to save your file in the right place.
You need to provide the full filepath
with open(r'C:\entire\path\to\file.txt', 'w') as f:
f.write('test')
If you just provide a file name without a path, it will use the current working directory, which isn't necessarily the directory where the python script your running is located. It will be the directory where you launched the script from.
C:\Users\admin> python C:\path\to\my_script.py
In this instance, the current working directory is C:\Users\admin, not C:\path\to.

Making a new file in subdirectories using python

I am trying to create a file in a subdirectory, both of which will not exist when the program is first run. When I do this:
newfile = open('abc.txt','w')
It will create abc.txt just fine but the following will cause an error, saying the file or directory does not exist
newfile = open('folder/abc.txt','w')
I tried using os.makedirs to create the directory first but that failed as well raising the same error. What is the best way to create both the folder and file?
Thanks
>>> import os
>>> os.makedirs('folder')
>>> newfile = open('folder' + os.sep + 'abc.txt', 'w')
>>> newfile.close()
>>> os.listdir('folder')
['abc.txt']
This works for me
A couple of things to check:
os.makedirs takes just the path, not the file. I assume you know this already, but you haven't shown your call to makedirs so I thought I'd mention it.
Consider passing an absolute, not a relative, path to makedirs. Alternatively, use os.chdir first, to change to a directory in which you know you have write permission.
Hope those help!

How do I create a file at a specific path?

In python I´m creating a file doing:
f = open("test.py", "a")
where is the file created? How can I create a file on a specific path?
f = open("C:\Test.py", "a")
returns error.
The file path "c:\Test\blah" will have a tab character for the `\T'. You need to use either:
"C:\\Test"
or
r"C:\Test"
I recommend using the os module to avoid trouble in cross-platform. (windows,linux,mac)
Cause if the directory doesn't exists, it will return an exception.
import os
filepath = os.path.join('c:/your/full/path', 'filename')
if not os.path.exists('c:/your/full/path'):
os.makedirs('c:/your/full/path')
f = open(filepath, "a")
If this will be a function for a system or something, you can improve it by adding try/except for error control.
where is the file created?
In the application's current working directory. You can use os.getcwd to check it, and os.chdir to change it.
Opening file in the root directory probably fails due to lack of privileges.
It will be created once you close the file (with or without writing). Use os.path.join() to create your path eg
filepath = os.path.join("c:\\","test.py")
The file is created wherever the root of the python interpreter was started.
Eg, you start python in /home/user/program, then the file "test.py" would be located at /home/user/program/test.py
f = open("test.py", "a") Will be created in whatever directory the python file is run from.
I'm not sure about the other error...I don't work in windows.
The besty practice is to use '/' and a so called 'raw string' to define file path in Python.
path = r"C:/Test.py"
However, a normal program may not have the permission to write in the C: drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.
Use os module
filename = "random.txt"
x = os.path.join("path", "filename")
with open(x, "w") as file:
file.write("Your Text")
file.close

Categories