How can I write users table data in custom file?
Your just need get your select put it in FOREACH and write down in file.(something like below code can help you_

$results= db_select('users','u')-&gt;fields('u',array('uid','name','email'))-&gt;execute()-&gt;fetchAll();
if($results){
     $fh=fopen(drupal_get_path('module',   'yourcustommodulename').'/usertest.txt','w+');
     foreach($results as $res){
     $string= 'uid:'.$res-&gt;uid.' ,name:'.$res-&gt;name.' ,email:'.$res-&gt;email.'\n\r';
    fwrite($fh,$string);
  }
  fclose($fh);


}