How to create a file in Filemanger in Code

Good day,
Am trying to create a file in file manager that is generated by code.

f = open("/files/autoname.xml", "wb")
f.write("file contente")

But the above code gives me an error.
FileNotFoundError: [Errno 2] No such file or directory: '/files/autoname.xml'

Something like this should work. Your goal is to create an instance of the 'File' DocType, and use it.


file_doc = frappe.get_doc(
    {
	"doctype": "File",
	"file_name": some_file_name,  # String that is your file's name
	"attached_to_doctype": None,
	"attached_to_name": None,
	"content": your_content,  # Your text/data content goes here.
	"folder": "Home"  #  If you want to save in subdirectory, enter 'Home/MySubdirectory'
  }
)
file_doc.save()

Now if you open the “Files” DocType in your browser, you should see a new file with your content.

7 Likes

Thank you, this worked, you are a life saver

i had file in a FileStorage type. so i had to extract content from it using my_file.read() then gave that value to content key. now i’m facing another problem that picture is saving 90° clockwise in when i preview in File Manager