python: get file path and create a new file in the same directory - python

So I know how to get a location of the needed file, I'm doing this with
file_name = os.path.splitext(os.path.basename(file_full_name))[0]
but what I need to do is:
Get the file name, which I have
Get path of the file, which I also know how to get
Create a file in the same directory with a modified name, for example lets say I have a file called "data.csv" on Desktop. I would need to create a file called "data - results.csv" to Desktop.
I have only tried printing the new name, but the only result I have got with this code:
myresultcsvfile = os.path.splitext(os.path.basename(file_name))[0] + " - results.csv"
is this:
myfile: ('Book1 - Copy', ' - results.csv')
I'm clearly doing something wrong but I cant figure out what. And that's just the file name, I also need to add full path of the parent file to it (so that the end result would be "C:\users[username]\desktop\Book1 - copy - results.csv" in this case)

Try this:
full = 'C:\\ .. put here your path .. \\data.csv'
dir_name = os.path.dirname(full)
file_name = os.path.splitext(os.path.basename(full))[0]
output_file = dir_name + '\\' + file_name + ' - results.csv'

Related

Is there any way to create a folder with the same name as a variable and then put a JSON file on it in python?

Hi i am trying to create a folder that jas the same name of a variable and then write a JSON file inside that folder. Currently mi code looks something like this:
a = "name"
filename = "Configs/" + a + "/" + a
with open (filename, 'w') as f_obj:
json.dump(data, f_obj)
After that I get the following error:
FileNotFoundError : [Errno 2] no such file or directory : 'Configs/name/name'
When I try:
filename = "Configs/" + a
It works perfectly, I would appreciate any help, thanks in advance.
open can create new files to be written to, but it won't create new directories to put them in. The error you're getting is because the directory Configs/name doesn't exist - you need to create this first, then create the file inside of it. Here's one way to do this:
import json
from pathlib import Path
data = {} # whatever your data is
a = "name"
file_path = Path("Configs") / a / a
file_path.parent.mkdir(parents=True, exist_ok=True) # if these flags are right for you
file_path.write_text(json.dumps(data))

Need help creating a txt file in a folder which, is in the same directory

I'm pretty new to python. I have a homwork problem where we need to analyze corpora and then compare them. We also have to save the files as a .txt file after is has been processed with an attribute, the size.
So I need to create a .txt file in a seperate folder called trigram-models.
This folder is in the same directory as my python file. I think i have to use the os module but i'm not sure how.
Here is my code:
from langdetect import read_trigrams, trigram_table, write_trigrams
import os
def make_profiles(datafolder, profilefolder, size):
filelist = []
for file in os.listdir('./training'):
filelist.append(file)
print(filelist)
for file in filelist:
filen = "./training/"+file
print("fi", filen)
maketable = trigram_table(filen, size)
readdata = read_trigrams(filen)
#print("re", readdata)
splitname = str(file).split('-')
newname = splitname[0] + "." + str(size) + '.txt'
endtable = write_trigrams(readdata, newname)
return (endtable)
make_profiles("./training", "./trigram-models", 20)
To create a directory, I would use the following format which relies on a try / catch and prevents an error if the directory already exists:
dirName = 'tempDir'
try:
# Create target Directory
os.mkdir(dirName)
print("Directory " , dirName , " Created ")
except FileExistsError:
print("Directory " , dirName , " already exists")
To change your directory you can use the following:
os.chdir(directoryLocation)
I recommend reading chapter 8 in automating the boring stuff with python.
I hope this helps. If you have any questions please don't hesitate to ask.
First of all, be sure to indent all the code in your method for it to be appropriately enclosed.
You are also passing relative paths (datafolder, profilefolder) for your folders as method arguments, so you should use them inside the method instead.
Lastly, to create a file in a folder, I would recommend using the following algorithm:
file_path = '/'.join(profilefolder, newname)
with open(file_path, 'w') as ouf:
ouf.write(endtable)
You will probably need to replace "endtable" with a string representation of your data.
Hope it helps.
As to clarify on toti08's answer, you should replace os.absdir with os.path.absdir.
filelist = [os.path.abspath(f) for f in os.listdir(data_folder)]
instead of
filelist = [os.abspath(f) for f in os.listdir(data_folder)]
Your function is not using the argument profileFolder, where you specify the name of the output directory. So first of all you should use this information for creating a folder before processing your files.
So first thing would be to create this output directory.
Second is to save your files there, and to do that you need to append the file name to the output directory. Something like this:
def make_profiles(data_folder, output_folder, size):
filelist = []
for file in os.listdir(data_folder):
filelist.append(file)
# Create output folder
if not os.path.exists(output_folder):
os.mkdir(output_folder)
for file in filelist:
filen = "./training/"+file
#print("fi", filen)
splitname = str(file).split('-')
# Create new file by appending name to output_folder
newname = os.path.join(output_folder, splitname[0] + "." + str(size) + '.txt')
return (endtable)
make_profiles(./training, './trigram-models', 20)
Note that you can also specify the relative folder name (i.e. "trigram-models" only) and then create the output directory by appending this name to the current path:
output_folder = os.path.join(os.getcwd(), output_folder)
Also (not related to the question) this piece of code could be optimized:
filelist = []
for file in os.listdir(data_folder):
filelist.append(file)
os.listdir already returns a list, so you could directly write:
filelist = os.listdir(data_folder)
But since you're interested in the absolute path of each file you could better do:
filelist = [os.path.abspath(f) for f in os.listdir(data_folder)]
where you basically take each file returned by os.listdir and you append its absolute path to your file list. Doing this you could avoid the line filen = "./training/"+file.
So in the end your code should look something like this:
def make_profiles(data_folder, output_folder, size):
filelist = [os.abspath(f) for f in os.listdir(data_folder)]
# Create output folder
if not os.path.exists(output_folder):
os.mkdir(output_folder)
for file in filelist:
splitname = str(file).split('-')
# [...add other pieces of code]
# Create new file by appending name to output_folder
newname = os.path.join(output_folder, splitname[0] + "." + str(size) + '.txt')
# [...add other pieces of code]
return (endtable)
make_profiles(./training, './trigram-models', 20)

how to rename file in a directory using python

I have a file named "x.mkv" in a folder named "export". X could be anything.. it's not named exactly X, it's just file with some name.
I want to rename the file to "Movie1 x [720p].mkv". I want to keep the file's original name and add Movie1 as prefix and [720p] as a suffix.
There is just one file in the folder, nothing more.
How do I do so?
I tried using variables in os.rename and i failed.. this is what I used :
import os
w = os.listdir("C:/Users/UserName/Desktop/New_folder/export")
s = '[Movie1]' + w + '[720p]'
os.rename(w,s)
What I'm trying to do is... get the file name from the folder, as there is and will be only 1 file, so, this seems appropriate.
saving the fetch results in 'w' and then using another variable 's' and adding prefix and suffix. Then at the end, I fail at using the variables in 'os.rename' command.
Your original won't work for a few reasons:
os.listdir() returns a list and not a string so your string concatenation will fail.
os.rename() will have trouble renaming the file unless the path is given or you change the cwd.
I'd suggest the following code:
import os
path="C:/Users/UserName/Desktop/New_folder/export/"
w = os.listdir(path)
#since there is only one file in directory it will be first in list
#split the filename to separate the ext from the rest of the filename
splitfilename=w[0].split('.')
s = '[Movie1]' + '.'.join(splitfilename[:-1]) + '[720p].'+splitfilename[-1]
os.rename(path+w[0],path+s)
Use os.rename:
def my_rename(path, name, extension, prefix, suffix):
os.rename(path + '/' + old_name + '.' + extension,
path + '/' + prefix + old_name + suffix + '.' + extension)
my_rename('/something/export', 'x', 'mkv', 'Movie1 ', ' [720p]')

Create file in sub directory Python?

In my Python script, I need to create a new file in a sub directory without changing directories, and I need to continually edit that file from the current directory.
My code:
os.mkdir(datetime+"-dst")
for ip in open("list.txt"):
with open(ip.strip()+".txt", "a") as ip_file: #this file needs to be created in the new directory
for line in open("data.txt"):
new_line = line.split(" ")
if "blocked" in new_line:
if "src="+ip.strip() in new_line:
#write columns to new text file
ip_file.write(", " + new_line[11])
ip_file.write(", " + new_line[12])
try:
ip_file.write(", " + new_line[14] + "\n")
except IndexError:
pass
Problems:
The path for the directory and file will not always be the same, depending on what server I run the script from. Part of the directory name will be the datetime of when it was created ie time.strftime("%y%m%d%H%M%S") + "word" and I'm not sure how to call that directory if the time is constantly changing. I thought I could use shutil.move() to move the file after it was created, but the datetime stamp seems to pose a problem.
I'm a beginner programmer and I honestly have no idea how to approach these problems. I was thinking of assigning variables to the directory and file, but the datetime is tripping me up.
Question: How do you create a file within a sub directory if the names/paths of the file and sub directory aren't always the same?
Store the created directory in a variable. os.mkdir throws if a directory exists by that name.
Use os.path.join to join path components together (it knows about whether to use / or \).
import os.path
subdirectory = datetime + "-dst"
try:
os.mkdir(subdirectory)
except Exception:
pass
for ip in open("list.txt"):
with open(os.path.join(subdirectory, ip.strip() + ".txt"), "a") as ip_file:
...
first convert the datetime to something the folder name can use
something like this could work
mydate_str = datetime.datetime.now().strftime("%m-%d-%Y")
then create the folder as required
- check out
Creating files and directories via Python
Johnf

Why is my write function not creating a file?

According to all the sources I've read, the open method creates a file or overwrites one with an existing name. However I am trying to use it and i get an error:
File not found - newlist.txt (Access is denied)
I/O operation failed.
I tried to read a file, and couldn't. Are you sure that file exists? If it does exist, did you specify the correct directory/folder?
def getIngredients(path, basename):
ingredient = []
filename = path + '\\' + basename
file = open(filename, "r")
for item in file:
if item.find("name") > -1:
startindex = item.find("name") + 5
endindex = item.find("<//name>") - 7
ingredients = item[startindex:endindex]
ingredient.append(ingredients)
del ingredient[0]
del ingredient[4]
for item in ingredient:
printNow(item)
file2 = open('newlist.txt', 'w+')
for item in ingredient:
file2.write("%s \n" % item)
As you can see i'm trying to write the list i've made into a file, but its not creating it like it should. I've tried all the different modes for the open function and they all give me the same error.
It looks like you do not have write access to the current working directory. You can get the Python working directory with import os; print os.getcwd().
You should then check whether you have write access in this directory. This can be done in Python with
import os
cwd = os.getcwd()
print "Write access granted to current directory", cwd, '>', os.access(cwd, os.W_OK)
If you get False (no write access), then you must put your newfile.txt file somewhere else (maybe at path + '/newfile.txt'?).
Are you certain the directory that you're trying to create the folder in exists?
If it does NOT... Then the OS won't be able to create the file.
This looks like a permissions problem.
either the directory does not exist or your user doesn't have the permissions to write into this directory .
I guess the possible problems may be:
1) You are passing the path and basename as parameters. If you are passing the parameters as strings, then you may get this problem:
For example:
def getIngredients(path, basename):
ingredient = []
filename = path + '\\' + basename
getIngredients("D","newlist.txt")
If you passing the parameters the above way, this means you are doing this
filename = "D" + "\\" + "newlist.txt"
2) You did not include a colon(:) after the path + in the filename.
3) Maybe, the file does not exist.

Categories

Resources