开发者

Iterating over os.walk in linux

开发者 https://www.devze.com 2023-02-21 17:21 出处:网络
We have multiple linux server and i would like to get all the details of files and directories in a particular linux server. I know this can be done with os.walk function but it is storing only single

We have multiple linux server and i would like to get all the details of files and directories in a particular linux server. I know this can be done with os.walk function but it is storing only single file information. Please find the below code

import os
for d in os.walk('/'):
    F = open('/home/david/De开发者_StackOverflow社区sktop/datafile.txt', 'w')
    F.write(str(d) + '\n')
    F.close()

Thanks in advance


You could use a context manager

import os
with open('/home/david/Desktop/datafile.txt', 'w') as F:
    for d in os.walk('/'):
        F.write(str(d) + '\n')


You should append to the file rather than just write to it (which resets the file contents each time you open it). To enable append mode, pass a instead of w.

However, there is no need to do so - simply open the file once and keep writing to it rather than re-opening the file handle every loop iteration (that's a tremendous waste of time!).

F = open('/home/david/Desktop/datafile.txt', 'w')
for d in os.walk('/'):
  F.write(str(d) + '\n')
F.close()

You can also use a with-statement, which automates the close() for you.

with open(...) as F:
      for d in ..
         ...


Re-creating the same file within each iteration does not make any sense. Either you move the open() outside the loop or you re-open the file inside the loop using append-mode 'a'.


You are getting only one entry because your file writes are not being appended, they are creating the file from scratch.

Also, see the documentation for os.walk(). A list of files in each folder visited is given:

import os
f=file(r'/home/david/Desktop/datafile.txt', 'a') # <---- Note "a"
for root, files, dirs in os.walk('/'):
    f.write('Currently in: ' + root + '\n')
    f.write(' '*4 + 'Files:\n')
    for ff in files:
        f.write(' '*8 + ff + '\n')
    f.write(' '*4 + 'Folders:\n')
    for ff in dirs:
        f.write(' '*8 + ff + '\n')
0

精彩评论

暂无评论...
验证码 换一张
取 消