Saturday 2 November 2013

How to read files of computer drive in network using python



We can read all files of local computer or remote computer drives.

If you want to read local computer drive files then use below code.
import os
import re
import win32api

def  find_file(root_folder, rex):

    for root,dirs,files in os.walk(root_folder):
        for f in files:
            result = rex.search(f)
            if result:
                x = os.path.join(root,f)
                datafile = file(x)
                for line in datafile:
                    if 'ca' in line:
                        print x
file_name = ''
rex = re.compile(file_name)
for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]:
    if drive=='E:\\':
        find_file( drive, rex )

If you want to read remote file then first you have to make connection by 2 ways

    1) You have to mount remote system drive in to your local system or

    2) You have to set netuse virtual connection

import win32api
import win32net

ip = '192.168.1.18'
username = 'ram'
password = 'ram@123'

use_dict={}
use_dict['remote']=unicode('\\\\192.168.1.18\C$')
use_dict['password']=unicode(password)
use_dict['username']=unicode(username)
win32net.NetUseAdd(None, 2, use_dict)

images = ['*.doc', '*.docx', '*.csv', '*.txt', '*.pdf', '*.xlx', '*.xlsx']
matches = []

for root, dirnames, filenames in os.walk('\\\\192.168.1.18\C$'):
    for extensions in images:
        for filename in fnmatch.filter(filenames, extensions):
            match=os.path.join(root, filename)
            datafile = file(match)
            for line in datafile:
               print line

it will read all files line by line there you can read whatever you want.

Thanks Guys

No comments:

Post a Comment