0

I was working on saving text to different files. so, now I already created several files and each text file has some texts/paragraph in it. Now, I just want to save these files to a directory. I already created a self-defined directory, but now it is empty. I want to save these text files into my directory.

The partial code is below:

for doc in root:
    docID = doc.find('DOCID').text.strip() 
    text = doc.find('TEXT').text,strip() 
    f = open("%s" %docID, 'w') 
    f.write(str(text))

Now, I created all the files with text in it. and I also have a blank folder/directory now. I just don't know how to put these files into the directory. I would be appreciate it.

======================================================================== [Solved] Thank you guys for your all helping! I figured it out. I just edit my summary here. I got a few problems. 1. my docID was saved as tuple. I need to convert to string without any extra symbol. here is the reference i used: https://stackoverflow.com/a/17426417/9387211 2. I just created a new path and write the text to it. i used this method: https://stackoverflow.com/a/8024254/9387211

Now, I can share my updated code and there is no more problem here. Thanks everyone again!

for doc in root:
   docID = doc.find('DOCID').text.strip()
   did = ''.join(map(str,docID))
   text = doc.find('TEXT').text,strip() 
   txt = ''.join(map(str,docID))
   filename = os.path.join(dst_folder_path, did)
   f = open(filename, 'w') 
   f.write(str(text))
Maryg
  • 105
  • 3
  • 12

2 Answers2

0

Suppose you have all the text files in home directory (~/) and you want to move them to /path/to/dir folder.

from shutil import copyfile
import os
docid_list = ['docid-1', 'docid-2']
for did in docid_list:
    copyfile(did, /path/to/folder)
    os.remove(did)

It will copy the docid files in /path/to/folder path and remove the files from the home directory (assuming you run this operation from home dir)

Osman Mamun
  • 2,864
  • 1
  • 16
  • 22
  • Thanks for you answer, but I think there might be some other problems in my code, the remove function is not working...I am still trying.. – Maryg Feb 25 '18 at 18:20
  • are you importing os? – Osman Mamun Feb 25 '18 at 20:16
  • I do include it. :| – Maryg Feb 26 '18 at 17:44
  • Thanks for your helping! I figure out. Instead of using "copyfile", I used copy. the reference is here: https://stackoverflow.com/a/45126659/9387211. This allow me to specify a folder as the destination. – Maryg Feb 28 '18 at 20:06
  • Aha, I got it. I always copy file from path/to/old/filename to path/to/new/file/name. And I haven't tested this code in console. – Osman Mamun Feb 28 '18 at 20:37
0

You can frame the file path for open like

doc_file = open(<file path>, 'w')
vumaasha
  • 2,765
  • 4
  • 27
  • 41