Why is File.separator using the wrong character? - path-separator

I'm trying to add functionality to a large piece of code and am having a strange problem with File Separators. When reading a file in the following code works on my PC, but fails when on a Linux server. When on PC I pass this and it works:
fileName = "C:\\Test\\Test.txt";
But when on a server I pass this and get "File Not Found" because the BufferedReader/FileReader statement below swaps "/" for "\":
fileName = "/opt/Test/Test.txt";
System.out.println("fileName: "+fileName);
reader = new BufferedReader(new FileReader(new File(fileName)));
Produces this output when run on the LINUX server:
fileName: /opt/Test/Test.txt
File Not Found: java.io.FileNotFoundException: \opt\Test\Test.txt (The system cannot find the path specified)
When I create a simple Test.java file to try and replicate it behaves as expected, so something in the larger code source is causing the BufferedReader/FileReader line to behave as if it's on a PC, not a Linux box. Any ideas what that could be?

I don't see where you used File.separator. Try this instead of hard coding the path separators.
fileName = File.separator + "opt" + File.separator + "Test" + File.separator + "Test.txt";

Related

Matlab Script Problem between Linux and Windows

I wrote a script in Matlab on windows system. Now I changed to linux system and I tried to use my script on linux in matlab also. But it does not work.
I got a problem with the data import part of my script:
data = {};
for i = 1:numel(filelist)
filename = filelist{i};
filename = [selpath '\' filename];
delimiter = ',';
startRow = 2;
formatSpec = '%*q%*q%*q%q%[^\n\r]';
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'TextType', 'string', 'HeaderLines' ,startRow-1, 'ReturnOnError', false, 'EndOfLine', '\r\n');
fclose(fileID);
tmp_data = str2double(dataArray{1});
data{i} = tmp_data;
end
If I run my script I got the following error from matlab:
Error using textscan
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in justus_tem (line 21)
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'TextType', 'string', 'HeaderLines' ,startRow-1, 'ReturnOnError',
false, 'EndOfLine', '\r\n');
When I run the same script on windows I do not get the Error. In linux system the fileID is always -1
Has somebody a tip or knows what I do wrong? I tried different permissions for fopen but it does not work either.
Linux uses a forward slash (/) as the file separator, you have hard-coded the Windows compatible backward slash (\). Instead, consider either
Using filesep for a system-dependent file separator
filename = [selpath, filesep, filename];
Or use fullfile to build the path for you
filename = fullfile(selpath, filename);

Python3 _io.TextIOWrapper error when opening a file with notepad

I am stuck from a couple of days on an issue in my micro Address Book project. I have a function that writes all records from a SQLite3 Db on file in order to open in via OS module, but as soon as I try to open the file, Python gives me the following error:
Error while opening tempfile. Error:startfile: filepath should be string, bytes or os.PathLike, not _io.TextIOWrapper
This is the code that I have to write records on file and to open it:
source_file_name = open("C:\\workdir\\temp.txt","w")
#Fetching results from database and storing in result variable
self.cur.execute("SELECT id, first_name, last_name, address1, address2, zipcode, city, country, nation, phone1, phone2, email FROM contacts")
result = self.cur.fetchall()
#Writing results into tempfile
source_file_name.write("Stampa Elenco Contatti\n")
for element in result:
source_file_name.write(str(element[0]) + "|" + str(element[1]) + "|" + str(element[2]) + "|" + str(element[3]) + "|" + str(element[4]) + "|" + str(element[5]) + "|" + \
str(element[6]) + "|" + str(element[7]) + "|" + str(element[8]) + "|" + str(element[9]) + "|" + str(element[10]) + "|" + str(element[11]) + "\n")
#TODO: Before exiting printing function you MUST:
# 1. filename.close()
# 2. exit to main() function
source_file_name.close()
try:
os.startfile(source_file_name,"open")
except Exception as generic_error:
print("Error while opening tempfile. Error:" + str(generic_error))
finally:
main()
Frankly I don't understand what this error means, in my previous code snippets I've always handled text files without issues, but I realize this time it's different because I am picking my stream from a database. Any ideas how to fix it?
Thanks in advance, and sorry for my english...
Your problem ultimately stems from poor variable naming. Here
source_file_name = open("C:\\workdir\\temp.txt","w")
source_file_name does not contain the source file name. It contains the source file itself (i.e., a file handle). You can't give that to os.startfile(), which expects a file path (as the error also says).
What you meant to do is
source_file_name = "C:\\workdir\\temp.txt"
source_file = open(source_file_name,"w")
But in fact, it's much better to use a with block in Python, as this will handle closing the file for you.
It's also better to use a CSV writer instead of creating the CSV manually, and it's highly advisable to set the file encoding explicitly.
import csv
# ...
source_file_name = "C:\\workdir\\temp.txt"
with open(source_file_name, "w", encoding="utf8", newline="") as source_file:
writer = csv.writer(source_file, delimiter='|')
source_file.write("Stampa Elenco Contatti\n")
for record in self.cur.fetchall():
writer.writerow(record)
# alternative to the above for loop on one line
# writer.writerows(self.cur.fetchall())

image processing commands in python using for loop

I have this part code which i don't understand the for loop part:
also what does file path holds and how it is different than all file path?
all_files_path = glob.glob("ADNI1_Screening_1.5T/ADNI/*/*/*/*/*.nii")
for file_path in all_file_path:
print(os.system("./runROBEX.sh " + file_path + " stripped/" +file_path.split("/")[-1]))

How to get the name of the directory from the name of the directory + the file

In an application, I can get the path to a file which resides in a directory as a string:
"/path/to/the/file.txt"
In order to write another another file into that same directory, I want to change the string "/path/to/the/file.txt" and remove the part "file.txt" to finally only get
"/path/to/the/"
as a string
I could use
string = "/path/to/the/file.txt"
string.split('/')
and then glue all the term (except the last one) together with a loop
Is there an easy way to do it?
You can use os.path.basename for getting last part of path and delete it with using replace.
import os
path = "/path/to/the/file.txt"
delete = os.path.basename(os.path.normpath(path))
print(delete) # will return file.txt
#Remove file.txt in path
path = path.replace(delete,'')
print(path)
OUTPUT :
file.txt
/path/to/the/
Let say you have an array include txt files . you can get all path like
new_path = ['file2.txt','file3.txt','file4.txt']
for get_new_path in new_path:
print(path + get_new_path)
OUTPUT :
/path/to/the/file2.txt
/path/to/the/file3.txt
/path/to/the/file4.txt
Here is what I finally used
iter = len(string.split('/'))-1
directory_path_str = ""
for i in range(0,iter):
directory_path_str = directory_path_str + srtr.split('/')[i] + "/"

Writing a groovy script results into a file

I would like to write groovy script results in to a file on my Mac machine.
How do I do that in Groovy?
Here my attempt:
log.info "Number of nodes:" + numElements
log.info ("Matching codes:"+matches)
log.info ("Fails:"+fails)
// Exporting results to a file
today = new Date()
sdf = new java.text.SimpleDateFormat("dd-MM-yyyy-hh-mm")
todayStr = sdf.format(today)
new File( "User/documents" + todayStr + "report.txt" ).write(numElements, "UTF-8" )
new File( "User/documents" + todayStr + "report.txt" ).write(matches, "UTF-8" )
new File( "User/documents" + todayStr + "report.txt" ).write(fails, "UTF-8" )
Can anyone help in the exporting results part?
Thanks,
Regards,
A
ok, i've managed to create a file with
file = new File(dir + "${todayStr}_report.txt").createNewFile()
How do I add the numelements,matches and fails? like this:
File.append (file, matches)?
I get the follwoing error:
groovy.lang.MissingMethodException: No signature of method: static java.io.File.append() is applicable for argument types: (java.lang.Boolean, java.util.ArrayList) values: [true, [EU 4G FLAT L(CORPORATE) SP, EU 4G FLAT M(CORPORATE), ...]] Possible solutions: append(java.lang.Object, java.lang.String), append(java.io.InputStream), append(java.lang.Object), append([B), canRead(), find() error at line: 33
You have wrong filepath. I don't have MAC so I'm not 100% sure but from my point of view you should have:
new File("/User/documents/${todayStr}report.txt").write(numElements, "UTF-8")
You lack at least two backslashes, first before User and second after documents in your path. With the approach you have now, it tries to save to a directory User/documentDATE, pretty sure it does not exist.
So above I showed you way with absolute path. You can also write strictly like this:
new File("${todayStr}report.txt").write(numElements, "UTF-8")
and if the file is created then you'll be 100% sure it is a problem with your filepath :)
A few more things - since it is a groovy, try to use the advantages that language has over Java, there are several ways of working with files, I've also rewritten your logs to show you how simple it is to work with Strings in groovy:
log.info "Number of nodes: ${numElements}"
log.info "Matching codes: ${matches}"
log.info "Fails: ${fails}"
I hope it helps

Resources