craxsh
craxsh

Reputation: 35

matlab text read and write %s character (without escaping)

Dear All (with many thanks in advance),

The following script has trouble reading (and therefore writing) the %s character in the file 'master.py'.

I get that matlab thinks the %s is an escape character, so perhaps an option is to modify the terminator, but I have found this difficult.

(EDIT: Forgot to mention the file master.py is not in my control, so I can't modify the file to %%s for example).

%matlab script
%===============

fileID = fopen('script.py','w');  
yMax=5; 
fprintf(fileID,'yOverallDim = %d\n', -1*yMax);

%READ IN "master.py" for rest of script
fileID2 = fopen('master.py','r');

currentLine = fgets(fileID2);
while ischar(currentLine) 
    fprintf(fileID,currentLine);
    currentLine = fgets(fileID2);
end
fclose(fileID);  
fclose(fileID2);  

The file 'master.py' looks like this (and the problem is on line 6 'setName ="Set-%s"%(i+1)':

i=0
for yPos in range (0,yOverallDim,yVoxelSize):
    yCoordinate=yPos+(yVoxelSize/2) #
    for xPos in range (0,xOverallDim,xVoxelSize):
        xCoordinate=xPos+(xVoxelSize/2) 
        setName ="Set-%s"%(i+1)
        p = mdb.models['Model-1'].parts['Part-1']
        # p = mdb.models['Model-1'].parts['Part-2']
        c = p.cells
        cells = c.findAt(((xCoordinate, yCoordinate, 10.0), ))
        region = p.Set(cells=cells, name=setName)
        p.SectionAssignment(region=region, sectionName='Section-1', offset=0.0, offsetType=MIDDLE_SURFACE, offsetField='', thicknessAssignment=FROM_SECTION)
    i+=1

Upvotes: 1

Views: 184

Answers (3)

craxsh
craxsh

Reputation: 35

Thanks applesoup for identifying my fundamental oversight - the problem is in the fprintf - not in the file read

Thanks serial for enhancing the fprintf

Upvotes: 0

serial
serial

Reputation: 437

In the documentation of fprintf you'll find this:

fprintf(fileID,formatSpec,A1,...,An) applies the formatSpec to all elements of arrays A1,...An in column order, and writes the data to a text file.

So in your function fprintf uses currentLine as format specification, resulting in an unexpected output for line 6. Correct application of fprintf by providing a formatSpec, fixes this issue and doesn't require any replace operations:

fprintf(fileID, '%s', currentLine);

Upvotes: 1

applesoup
applesoup

Reputation: 487

Your script has no trouble reading the % characters correctly. The "problem" is with fprintf(). This function correctly interpretes the percent signs in the string as formatting characters. Therefore, I think you have to manually escape every single % character in your currentLine string:

currentLine = strrep(currentLine, '%', '%%');

At least, it worked when I checked it on your example data.

Upvotes: 0

Related Questions