Why is my write function not creating a file? - python

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.

Related

Is there a way to remove part of a file name (path) in python?

I have around 50 files that have their name and then the date they were created at 3 times. How can I remove that part from the file name in python (You can show an example with other data it doesn't really matter)
I tried something like that:
file = 'directory/imagehellohellohello.png'
keyword = 'hello'
if (file.count(keyword) >= 3):
//functionality (here I want to remove the hello's from the file path)
This can be done quite simply using pathlib:
from pathlib import Path
path = Path("directory/imagehellohellohello.png")
target = path.with_name(path.name.replace("hello", ''))
path.rename(target)
And this indeed renames the file to "directory/image.png".
From Python version 3.8 the rename method also returns the new files' path as a Path object. (So it is possible to do:
target = path.rename(path.with_name(path.name.replace("hello", '')))
Methods/attributes used: Path.rename, Path.with_name, Path.name, str.replace
file = 'directory/imagehellohellohello.png'
keyword = 'hello'
if keyword*3 in file:
newname = file.replace(keyword*3, '')
os.rename(file, newname)

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

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'

Abaqus Python script to open several odb files by variable name

I have a txt-file called "odbList.txt" which contains the names of several odb-files.
plate_2mm.odb
plate_4mm.odb
plate_6mm.odb
Now I wrote a Python Script, where I want to open each of these files in a loop.
# list of ODB-Files
odbList = [ ]
f = file( 'W:/someDirectory/odbList.txt' , 'r')
count = 0
for line in f.readlines() :
odbList.append (line)
count = count + 1
def getSIF(case, i):
odb = openOdb(path = 'W:/someDirectory/' + case)
# start analyses for each case
for i in xrange(0,count):
getSIF(odbList[i], i)
I get the following error message:
OdbError: Cannot open file W:/someDirectory/plate_2mm.odb
. *** ERROR: No such file: W:/someDirectory/plate_2mm.odb
The weird thing however is that it works perfectly fine when I hardcode the complete path.
Another weird thing. If I use this line instead:
odb = openOdb(path = case)
I get following error message:
OdbError: Cannot open file C:/Temp/plate_2mm.odb
. *** ERROR: No such file: C:/Temp/plate_2mm.odb
And if I transfer all my files into C:/Temp everything works fine. But why doesn't it work if I use the first version / a different folder? Especially since it is working when hardcoded.
Most of the times when I open a file I use the following:
f=open(file_name,'r')
s=f.read().splitlines()
f.close()
while '' in s:
s.remove('')
You will now have a list in s without enters.
Alternatively you can use something like
import os
odbList=[]
for fileN in os.listdir("."):
if '.odb' in fileN:
odbList.append(fileN)
This will find all files containing .odb in the name in the script's directory/working directory
Have you tried entering your string as a raw string like thisodb = openOdb(path = r'W:/someDirectory/' + case) or usining the os.sep character like this: odb = openOdb(path = 'W:someDirectory' + os.sep + case)

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

Matching MD5 Hashes from another script

Ok so i'm trying to create a script that does the following: Searches a directory for known hashes. Here is my first script:
Hash.py
import hashlib
from functools import partial
#call another python script
execfile("knownHashes.py")
def md5sum(filename):
with open(filename, mode='rb') as f:
d = hashlib.md5()
for buf in iter(partial(f.read, 128), b''):
d.update(buf)
return d.hexdigest()
print "Hash of is: "
print(md5sum('photo.jpg'))
if md5List == md5sum:
print "Match"
knownHashes.py
print ("Call worked\n")
md5List = "01071709f67193b295beb7eab6e66646" + "5d41402abc4b2a76b9719d911017c592"
The problem at the moment is that I manually have to type in the file I want to find out the hash of where it says photo.jpg. Also, The I haven't got the md5List to work yet.
I want the script to eventually work like this:
python hash.py <directory>
1 match
cookies.jpg matches hash
So how can I get the script to search a directory rather than manually type in what file to hash? Also, how can I fix the md5List because that is wrong?
You can get a list of files in the current working directory using the following. This is the directory that you run the script from.
import os
#Get list of files in working directory
files_list = os.listdir(os.getcwd())
You can iterate through the list using a for loop:
for file in files_list:
#do something
As equinoxel also mentioned below, you can use os.walk() as well.
Simple little gist should solve most of your problems. Understandable if you don't like using OOP for this problem, but I believe all of the important conceptual pieces are here in a pretty clean, concise representation. Let me know if you have any questions.
class PyGrep:
def __init__(self, directory):
self.directory = directory
def grab_all_files_with_ending(self, file_ending):
"""Will return absolute paths to all files with given file ending in self.directory"""
walk_results = os.walk(self.directory)
file_check = lambda walk: len(walk[2]) > 0
ending_prelim = lambda walk: file_ending in " ".join(walk[2])
relevant_results = (entry for entry in walk_results if file_check(entry) and ending_prelim(entry))
return (self.grab_files_from_os_walk(result, file_ending) for result in relevant_results)
def grab_files_from_os_walk(self, os_walk_tuple, file_ending):
format_check = lambda file_name: file_ending in file_name
directory, subfolders, file_paths = os_walk_tuple
return [os.path.join(directory, file_path) for file_path in file_paths if format_check(file_path)]

Categories

Resources