Matlab Script Problem between Linux and Windows - linux

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);

Related

Striping a string from newline markers

I store configuration data (paths to specific files) inside a file named app.cfg that looks like this :
path/to/config.json
path/to/default/folder
and I query those item with the following Python code:
with open("app.cfg","r",newline='') as config:
data = config.readlines()
PathToConfig = data[0]
DefaultPath = data[1]
config.close()
But when I use PathToConfig in my script, the path stored in this variable cannot be used because there is \n at the end of the string.
I tried to fix this issue by using this PathToConfig = data[0].rstrip() but there still is \n at the end of the string.
How can I strip this string from the newline marker ?
You should be able to solve it with .rstrip to strip "\n":
create app.cfg:
with open("app.cfg","w",newline='') as config:
config.writelines("""path/to/config.json
path/to/default/folder""")
app.cfg looks like this:
read contents from file:
with open("app.cfg","r",newline='') as config:
data = config.readlines()
PathToConfig = data[0].rstrip("\n")
DefaultPath = data[1]
output:

Using pandas to save to a csv file with date time appended to the filename

I was running the code but am getting this error
OSError: [Errno 22] Invalid argument: 'filename 09-30-2021 16:45:17 PM.csv'
Is there anyway to work around this?
currentDateTime = datetime.now().strftime("%m-%d-%Y %H:%M:%S %p")
df.to_csv(f"filename {currentDateTime}.csv", index = False)
Your example works on Linux, but it doesn't work on Windows because of the restricted characters: < > : " / \ | ? *
Please replace : with something else.
Try this instead. Because, you cannot have colons (:) in filenames.
currentDateTime = datetime.now().strftime("%m-%d-%Y %H-%M-%S %p")
df.to_csv(f"filename {currentDateTime}.csv", index = False)

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] + "/"

Why is File.separator using the wrong character?

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";

Unable to execute child_process.exec() when path has spaces

I am using appjs * and I want to execute a command to open a folder.
What I have
var path = __dirname + '/folder to open/';
// path = C:\Program Files\myapplication/folder to open/
require("child_process").exec("start " + path);
Error
Could not find file C:\Program
What I tried
I already tried to escape the spaces, that didn't work.
var path = __dirname + '/folder to open/';
path = path.replace(' ', '\ ');
// path = C:\Program Files\myapplication/folder to open/
require("child_process").exec("start " + path);
When I put the path between quotes, No folder is opened, only another prompt.
var path = "\"" + __dirname + "/folder to open/\"";
path = path.replace(' ', '\ ');
// path = "C:\Program Files\myapplication/folder to open/"
require("child_process").exec("start " + path);
Related bug https://github.com/isaacs/npm/pull/2479
Does anyone has a fix or a workaround?
* link removed
To open a path than contains spaces, you must replace with a double backslash.
In your code you escaped the space character:
"\ "
What you need to do is escape the backslash character so it makes it into the output string:
"\\ "
Try this:
var path = __dirname + '/folder to open/';
// Notice the double-backslashes on this following line
path = path.replace(/ /g, '\\ ');
require("child_process").exec("start " + path);
Well, I fixed it.
Or something like it.
Instead of using
"start " + path
I used
"%SystemRoot%\\explorer.exe \"" + path + "\""
Notice the quotes and the forward slashes.
In my case it is fixed by adding double quotes for the path except the first drive name or letter.
import * as path from 'path'; // npm module
const filePath = 'C:/Program Files/my application/file to open/test.txt';
const rootName = path.parse(filePath).root; // "C:/"
const filePathTo = `${rootName}"${filePath.replace(rootName, '')}"`; // C:/"Program Files/my application/file to open/test.txt"
require("child_process").exec(`start ${filePathTo}`);
The text file will be opened.
this works for me
f= file.replace(/ /g,"\\\ ")
You can also use the old-style 8-character-max/no-space names for each path.
The one I always used was always coding c:\PROGRA~1 instead of c:\Program Files, although this only works on english systems.
If the first 8 characters of any path with more chars are unique, I expect you can do something like newPath = origPath.sub(/\W/g, '').substr(0, 6) + "~1"
Don't have a windows system here, just going by memory.

Resources