How to programmatically assign (attach) a file to file field while creating/saving the node? I'm trying to assign (not upload) files to nodes programmatically.
This is the scenario:
I will create 2000 nodes and there are 2000 PDF files (one PDF per node). I don't want to upload these files via Drupal interface. I will upload all these PDF files via FTP.
These PDF files are well-named, I mean all of them have a standardized name such as {field_magazine_name}-{field_issue_number}.pdf (under sites/default/files/pdf for example).
What I want to do is to assign these PDF files to related nodes while creating/saving the nodes.

Possible Method 1
One method to do this would be to use the File Field Sources module.

I think remote file transfer can be used with some JavaScript code. The remote file transfer input can be automatically filled with the fields I want and it will work (for example http://example.com/sites/default/files/pdf/{field_magazine_name}-{field_issue_number}.pdf)... but I don't create nodes manually, I'm creating the nodes via Feeds. So, using JavaScript isn't the method I can use.
Is there any way to programmatically assign (attach) a file to file field while creating/saving the node?
I had a similar situation. My situation is attach a file to a node in the creation of a different content type node. Done this in hook_node_insert 


Initially i uploaded all files into a temp directory in /default/files/.
Then for each node, i created a new file object with my file attributes.
Then moved that particular file into the destination where i want the files to be placed. This results a clean complete file object with fid.
Then simply assign this file object attributes to file field and save the node.


The code used is follows..

$source_node = node_load($nid);
$filename = $bio_file_name; //your specific filename 
$dir = 'public://temp-path/'.$filename; //path to specific file with name
$file_size = filesize($dir);

//New file object
$file = new stdClass;
$file-&gt;uid = $source_node-&gt;uid;
$file-&gt;filename = $filename;
$file-&gt;uri = $dir;
$file-&gt;filemime = file_get_mimetype($dir);
// Make it permanent, otherwise it will get deleted later.
$file-&gt;status = FILE_STATUS_PERMANENT;
// Save file object to make it a 'managed file'.
$file_obj = file_move($file, 'public://newpath', FILE_EXISTS_REPLACE);

$source_node-&gt;your-file-field-name['und'][0] = array(
 'fid'  =&gt; $file_obj-&gt;fid,
 'uid'  =&gt; $file_obj-&gt;uid,
 'filename'  =&gt; $file_obj-&gt;filename,
 'uri'  =&gt; $file_obj-&gt;uri,
 'filemime'  =&gt; $file_obj-&gt;filemime,
 'filesize'  =&gt; $file_obj-&gt;filesize,
 'status'  =&gt; 1,
 'display'  =&gt; 1,
 'description'  =&gt; '', 
 );

 node_save($source_node); 


Hope this will help you..