I would like to ask you about the order in which Python folders are written.
If you run the following sample, you will see
importos
def asxmake(srcDir):
for subinos.listdir(srcDir):
newSrcPath=os.path.join(srcDir, sub)
ifos.path.isdir(newSrcPath):
f=open(AsxMake, 'a+')
print>>f, sub
print sub
asxmake (newSrcPath)
else:
f=open(AsxMake, 'a+')
file=sub.replace('/', '\\')
filename = os.path.basename(file)
print>>f, sub
print sub
srcDir='C:\\temp\\test'
AsxMakefall='C:\\temp\\test'
AsxMake='C:\\temp\\test\\1.asx'
asxmake(srcDir)
If you look at the written file, you can see
(The top tier is 01.txt02.txt
We are testing with 03.txt04.txt in the 00 folder structure.)
US>03.txt
04.txt
00
US>01.txt
US>02.txt
It will be
If you look at the print statement, the order of processing is as follows.
00
US>03.txt
04.txt
US>01.txt
US>02.txt
What causes the order to change?
I am a beginner in the program, so I cannot find a solution.
I look forward to your kind cooperation.
It is easy to understand if you keep in mind that the files are buffered.
Buffering is stored in memory before writing to a file, and when a certain amount is accumulated or the file is closed, it is written to a file.
This time, it is recursive, so the output of the recursive is written first.
00=>Buffer 1
03.txt = > Buffer 2
04.txt=>Buffer 2
Buffer 2 writeout
01.txt=>Buffer 1
02.txt = > Buffer 1
buffer 1 export
It is written in the order of buffer 2 and buffer 1, so the results are as described.
One way to get rid of this is to use flush.
def asxmake(srcDir):
for subinos.listdir(srcDir):
newSrcPath=os.path.join(srcDir, sub)
ifos.path.isdir(newSrcPath):
f=open(AsxMake, 'a+')
print>>f, sub
f.flush()
print sub
asxmake (newSrcPath)
else:
f=open(AsxMake, 'a+')
file=sub.replace('/', '\\')
filename = os.path.basename(file)
print>>f, sub
f.flush()
print sub
However, I think it would be easier to use walk instead of opening the file every time.
Once you open the file, you can use the same file handler to write it down.
importos
def asxmake(f,srcDir):
for subinos.listdir(srcDir):
newSrcPath=os.path.join(srcDir, sub)
ifos.path.isdir(newSrcPath):
print>>f, sub
asxmake(f, newSrcPath)
else:
file=sub.replace('/', '\\')
filename = os.path.basename(file)
print>>f, sub
srcDir='C:\\temp\\test'
AsxMakefall='C:\\temp\\test'
AsxMake='C:\\temp\\test\\1.asx'
with open(AsxMake, 'w') as f:
asxmake(f,srcDir)
© 2024 OneMinuteCode. All rights reserved.