I read the files in a directory using glob, and then I rename each file to something more legible for my purposes using os.rename.
for file_name in glob.glob(path+'*.txt'):
newfilename = 'run'+str(i)+'.csv' # rename filenames to something more readable
os.rename(file_name,path + newfilename) #put r before path if error ="(unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape"
When I try to write the each new file created into an array (a list) previously intialized to :
filelist=[];
using
filelist.append(i)=newfilename
I get the following error: "SyntaxError: cannot assign to function call"
If I just try to add the file to the filelst array using indeces, ie, filelist[i]=newfilename, I then get an index out of range error.
How do I do create this list of renamed filenames "on the fly"? Thank you.
Ok..so I finally understood that append wants to "append the "thing" to the list, as opposed to "append the thing at index i to the list" like I was trying to do originally.
So the correct way to use append is:
filelist.append(newfilename)
This question already has answers here:
Convert integers to strings to create output filenames at run time
(9 answers)
Closed 2 years ago.
As there are lots of folders and files, I wish to use loop to open the folder and read them.
The names of the folders to open and read them are rt20, rt30, rt40 and so on. Whereas, the names of the folders to save some text files are sphere20, sphere30, etc.
I created an array of characters and concatenate with the name of the folders but failed.
The actual code that I created is:
PROGRAM TEST1
IMPLICIT NONE
INTEGER ::lskip,lread,count
INTEGER :: n,I,j
REAL l,b,c,d,e,ReThe,ImThe,RePhi,ImPhi
CHARACTER(len=100) :: FN,FNL
character*2,parameter :: A(*) = ['20','30','40','50','60','70']
N=256
do j = 1,6
OPEN(11,file='rt',A(j),'\\output.dat',form='formatted')
!--allocate your vectors here
DO I=1,N
WRITE(FN,10)I
WRITE(6,*)FN
OPEN(1,FILE=FN)
!skip first 17 lines
do lskip = 1,18
READ(1,*)
end do
! Now read actual lines
do lread = 1,1
READ(1,*)l,b,ReThe,ImThe,RePhi,ImPhi,c,d,e
end do
write(11,20)ReThe,ImThe,RePhi,ImPhi
CLOSE(1)
END DO
10 format ('pm\\vertical\\sphere',A(j),'\\n_FarField',I0,'.ffe')
20 format (E14.7,4X,E14.7,4X,E14.7,4X,E14.7)
end do
END PROGRAM
The errors that are appeared in the program:
In file C:\Users\Hamsalekha\Desktop\far_field_sphere\Source1.f:12
OPEN(11,file='rt',A(j),'\\output.dat',form='formatted')
1
Error: Syntax error in OPEN statement at (1)
In file C:\Users\Hamsalekha\Desktop\far_field_sphere\Source1.f:33
10 FORMAT('pm\\vertical\\sphere',A(j),'\\n_FarField',I0,'.ffe')
1
Error: Unexpected element in format string at (1)
I couldn't find a solution on any websites. I really appreciate if someone can help me to solve this problem or give any hint.
You are concatenating your strings incorrectly:
OPEN(11,file='rt',A(j),'\\output.dat',form='formatted')
This only asks for file "rt" and than adds some other strange arguments. You need
OPEN(11,file='rt'//A(j)//'/output.dat',form='formatted')
Be aware that \ does not work as an escaping character in Fortran strings and that / is the proper multiplatform character to separate directories in the hierarchy. Yes, even in MS Windows.
The // is the Fortran string concatenation operator.
Jean-Claude Arbaut mentions in the comment the reason for the other error. One needs a constant string in the FORMAT statement. I personally strongly prefer to use format strings in the write statements directly and also to put what I can in the output list:
WRITE(FN,'(3A,I0,A)') 'pm/vertical/sphere',A(j),'/n_FarField',I,'.ffe'
but there are many other ways to write it. You can concatenate the string. You can also use the FORMAT statement.
WRITE(FN,10) A(j), I
10 FORMAT('pm/vertical/sphere',A,'/n_FarField',I0,'.ffe')
Many examples can be found here: Convert integers to strings to create output filenames at run time
Could someone help me in writing a program that has to compile all the files in the directory and report error, if any. For which my program has to get the list of all files under the folder with its full path and store it in a temp-table and then it has to loop through the temp table and compile the files.
Below is a very rough start.
Look for more info around the COMPILE statement and the COMPILER system handle in the online help (F1).
Be aware that compiling requires you to have a developer license installed. Without it the COMPILE statement will fail.
DEFINE VARIABLE cDir AS CHARACTER NO-UNDO.
DEFINE VARIABLE cFile AS CHARACTER NO-UNDO FORMAT "x(30)".
ASSIGN
cDir = "c:\temp\".
INPUT FROM OS-DIR(cDir).
REPEAT:
IMPORT cFile.
IF cFile MATCHES "*..p" THEN DO:
COMPILE VALUE(cDir + cFile) SAVE NO-ERROR.
IF COMPILER:ERROR THEN DO:
DISPLAY
cFile
COMPILER:GET-MESSAGE(1) FORMAT "x(60)"
WITH FRAME frame1 WIDTH 300 20 DOWN.
END.
END.
END.
INPUT CLOSE.
Since the comment wouldn't let me paste this much into it... using INPUT FROM OS-DIR returns all of the files and directories under a directory. You can use this information to keep going down the directory tree to find all sub directories
OS-DIR documentation:
Sometimes, rather than reading the contents of a file, you want to read a list of the files in a directory. You can use the OS–DIR option of the INPUT FROM statement for this purpose.
Each line read from OS–DIR contains three values:
*The simple (base) name of the file.
*The full pathname of the file.
*A string value containing one or more attribute characters. These characters indicate the type of the file and its status.
Every file has one of the following attribute characters:
*F — Regular file or FIFO pipe
*D — Directory
*S — Special device
*X — Unknown file type
In addition, the attribute string for each file might contain one or more of the following attribute characters:
*H — Hidden file
*L — Symbolic link
*P — Pipe file
The tokens are returned in the standard ABL format that can be read by the IMPORT or SET statements.
I am fairly new to VBA, but not to coding in general. I have an Excel worksheet, part of which I need to export into a text file. However, to ensure the escape characters don't collide with anything written in the worksheet, and also to match up with how escape characters are handled in other (Java & C) apps at our company, I would like to use the ascii character "thorn".
Some languages that I know, like perl, will simply let you enter an escape character and the ascii number of the symbol. E.g., I could type "\231" in order to get "thorn". It seems this is not supported in VBA. Or if it is, I am not sure how.
Lastly, below is a brief snippet of how I imagine I would implement the code, with just the key statements. If you have a better suggestion, or know why this wouldn't be the best way, please let me know.
Open sFullPath For Output As #1
(... some code to capture the values to be written to the next line of the file ...)
sLine = Join(sValues, <the thorn character>)
Print #1, sLine
The code above would be placed within a loop that would regenerate "sValues", the set of relevant cells in the next row to be printed to the text file.
Thanks so much!
Regards,
Mike
To print an ASCII character using its code number, use the chr() function
Extended ASCII isn't standard across all platforms. For whatever reason, the number needed is 222.
So you would need
sLine = Join(sValues, chr(222))
Print #1, sLine
Try replacing <the thorn character> with Chr(254). Let me know how that goes.
I'm trying to write some lines of codes that select a range in excel but the index to the range has a syntax error any suggestions? Also I'm trying to save a XML file as an xlsm file with file names from the concactenation of two file names stored in an array and is getting a similar error.any suggestions??
Range (Allfiles(index)).select 'Allfiles is an array containing the file names ' type error
Activeworkbooks.saveas "c:\Allfiles(1):&:Allfiles (count).xlsm", fileformat=52 'error
When you get an "error", a useful "error message" will give you a hint as to what the problem is. By reading this message and acting upon it, you can debug your code step by step.
Activeworkbooks.SaveAs "c:\Allfiles(1):&:Allfiles (count).xlsm", FileFormat = 52
' Variable not defined ^
The way to specify arguments in VBA is with :=, not =. Let's correct that and run it again...
Activeworkbooks.SaveAs "c:\Allfiles(1):&:Allfiles (count).xlsm", FileFormat:=52
' ^ Variable not defined
It's called ActiveWorkbook, not Activeworkbooks. Let's correct that and run it once more...
ActiveWorkbook.SaveAs "c:\Allfiles(1):&:Allfiles (count).xlsm", FileFormat:=52
' ^ The file could not be accessed.
I can't claim to know for sure what OS you're running, but given the C:\, I'll assume some flavour of Windows. You may know that : is an illegal character in paths in Windows?
Anyhow, I'm not sure where you're trying to save this file. My best guess:
ActiveWorkbook.SaveAs "C:\" & Allfiles(1) & Allfiles(UBound(Allfiles)) & ".xlsm", _
FileFormat:=52
As for you first line of code, Range (Allfiles(index)).Select, I have no clue what you're trying to do there. You may want to read Excel-VBA's help file to learn what Range does.