Abaqus Python script to open several odb files by variable name - python

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)

Related

Reading file in the same folder - Improvement?

i am writing an python script. I was having some problems to open the file. The error was always that system just can not find the file.
Because of that i tried get the active path... Replace backslash ... and so on....
Is there any improvements to work with the file in the same folder?
The Code
import os
# The name of the txt file that is in the same folder.
myFile = 'noticia.txt'
# Getting the active script
diretorio = os.path.dirname(os.path.abspath(__file__))
# Replace BackSlash and concatenate myFile
correctPath = diretorio.replace("\\", "/") + "/" + myFile
# Open file
fileToRead = open(correctPath, "r")
# Store text in a variable
myText = fileToRead.read()
# Print
print(myText)
Note:
The script is in the same folder of the txt file.
Is there any improvements to work with the file in the same folder?
First off, please see PEP 8 for standard conventions on variable names.
correctPath = diretorio.replace("\\", "/") + "/" + myFile
While forward slashes are preferred when you specify a new path in your code, there is no need to replace the backslashes in a path that Windows gives you. Python and/or Windows will translate behind the scenes as necessary.
However, it would be better to use os.path.join to combine the path components (something like correct_path = os.path.join(diretorio, my_file)).
fileToRead = open(correctPath, "r")
# Store text in a variable
myText = fileToRead.read()
It is better to use a with block to manage the file, which ensures that it is closed properly, like so:
with open(correct_path, 'r') as my_file:
my_text = my_file.read()

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 function to parse file works for single file but not for batch

I have a function that removes part of each line of a tab delimited file, and then writes the information to a new file in a different location (with a different file extension). When I use the function on a single file, it works fine, but when I try to use it on every file in a directory (using os.listdir) I keep getting a list index out of range error. Below is my function:
def ext_edit(filename):
prefix = filename[0:-3]
mapfile = "location/of/new/file/" + prefix + "map"
with open(filename) as f:
with open (mapfile, "w") as out:
for line in f:
x = line.split("\t")
del x[2:4]
out.write(x[0])
out.write(" ")
out.write(x[1])
out.write("\n")
This works fine with a single file, but I get index out of range, with the error at out.write(x[1]). To test whether it would work just for x[0], I removed the latter part, but then I get a "No such file or directory: "filename.txt" error.
Below is my call to apply the function on multiple files:
for file in os.listdir("location/of/original/file"):
ext_edit(file)
Does anyone know where I am going wrong with this?
Based on the error result it's giving you ("No such file or directory: "filename.txt"), it might be that it's trying to open the file relative to your current working directory. You could either:
1) Use os.chdir("location/of/original/file") before your for loop:
os.chdir("location/of/original/file")
for file in os.listdir("location/of/original/file"):
ext_edit(file)
2) Or prefix the file argument with the directory path:
for file in os.listdir("location/of/original/file"):
ext_edit("location/of/original/file" + file)
I would, if possible, use the functions provided in os.path.
Call function needs the root, too:
for file in os.listdir("D:/_tmp/maps"):
ext_edit(os.path.join("D:/_tmp/maps", file))
The same for the function call:
def ext_edit(filename):
root, ext = os.path.splitext(filename)
prefix = os.path.basename(root)
mapfile = os.path.join("D:/_tmp/maps_new", prefix + "map" + ext)
with open(filename) as f:
with open (mapfile, "w") as out:
for line in f:
x = line.split("\t")
del x[2:4]
out.write(x[0])
out.write(" ")
out.write(x[1])
out.write("\n")

Opening multiple python files from folder

I am trying to take a folder which contains 9 files, each containing FASTA records of separate genes, and remove duplicate records. I want to set it up so that the script is called with the folder that contains the genes as the first parameter, and a new folder name to rewrite the new files without duplicates to. However, if the files are stored in a folder called results within the current directory it is not letting me open any of the gene files within that folder to process them for duplicates. I have searched around and it seems that I should be able to call python's open() function with a string of the file name like this:
input_handle = open(f, "r")
This line is not allowng me to open the file to read its contents, and I think it may have something to do with the type of f, which shows to be type 'str' when I call type(f)
Also, if I use the full path:
input_handle = open('~/Documents/Research/Scala/hiv-biojava-scala/results/rev.fa', "r")
It says that no such file exists. I have checked my spelling and I am sure that the file does exist. I also get that file does not exist if I try to call its name as a raw string:
input_handle = open(r'~/Documents/Research/Scala/hiv-biojava-scala/results/rev.fa', "r")
Or if I try to call it as the following it says that no global results exists:
input_handle = open(os.path.join(os.curdir,results/f), "r")
Here is the full code. If anybody knows what the problem is I would really appreciate any help that you could offer.
#!/usr/bin/python
import os
import os.path
import sys
import re
from Bio import SeqIO
def processFiles(files) :
for f in files:
process(f)
def process(f):
input_handle = open(f, "r")
records = list(SeqIO.parse(input_handle, "fasta"))
print records
i = 0
while i < len(records)-1:
temp = records[i]
next = records[i+1]
if (next.id == temp.id) :
print "duplicate found at " + next.id
if (len(next.seq) < len(temp.seq)) :
records.pop(i+1)
else :
records.pop(i)
i = i + 1
output_handle = open("out.fa", "w")
for record in records:
SeqIO.write(records, output_handle, "fasta")
input_handle.close()
def main():
input_folder = sys.argv[1]
out_folder = sys.argv[2]
if os.path.exists(out_folder):
print("Folder %s exists; please specify empty folder or new one" % out_folder)
sys.exit(1)
os.makedirs(out_folder)
files = os.listdir(input_folder)
print files
processFiles(files)
main()
Try input_handle = open(os.path.join(os.getcwd,results/f), "r"). os.curdir returns . See mail.python.org/pipermail/python-list/2012-September/631864.html.

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