问题
Previously, I have been able to create lists using a command similar to the following:
os.popen('ls *.fits > samplelist')
Now I'm attempting to organize the files into lists by grouping them by number.
The files are named as following:
Name_0000_J.fits, Name_0001_J.fits, Name_0002_J.fits, ect.
I've attempted to run this line of code but it just creates the list skylist_J_1 and leaves it empty.
os.popen('for num in {0000..0089} ; do ls Name_$num\_J.fits >> skylist_J_1 ; done')
I ran the above in a command line and it works perfectly. Any insight would be greatly appreciated.
Edit:
I have come up with this solution but it is rather bulky. Hopefully there is a cleaner way to accomplish this.
def MkSkylist(qmin,qmax,name,band,quadrant):
a = qmax-qmin+1
ran = np.arange(qmin,qmax+1)
num = [0]*a
i = 0
while i < a:
num[i] = np.array2string(ran[i]).zfill(4)
i = i + 1
os.popen('ls '+name+num[0]+'_'+band+'.fits > skylist_'+band+'_'+quadrant)
i = 1
while i < a:
os.popen('ls '+name+num[0]+'_'+band+'.fits >> skylist_'+band+'_'+quadrant)
i = i + 1
回答1:
The problem seems to be with the syntax of the for loop: even though that syntax is valid in bash, it seems Python doesn't like it. Not even with subprocess.Popen(..., shell=True)
.
So, try using seq instead:
os.popen("for num in $(seq 0 89); do printf "Name_%04dJ.fits\n" $num >> skylist_J_1; done");
Which generates a file skylist_J_1
with this content:
Name_0001J.fits
Name_0002J.fits
Name_0003J.fits
Name_0004J.fits
...
Name_0086J.fits
Name_0087J.fits
Name_0088J.fits
Name_0089J.fits
Also notice you can put the file redirection outside, which is more similar to your first example (using >
instead of >>
):
os.popen('for num in $(seq 0 89); do printf "Name_%04dJ.fits\n" $num; done > skylist_J_1')
来源:https://stackoverflow.com/questions/59621752/creating-a-list-in-python-using-os-popen