Noober
Noober

Reputation: 1626

How do create a text file in a specified location using python

I am trying to create a text file using python. Here is my code-

import sys
import os

str1="a1.txt"
file1="Documents/Inbox/"
completeName=file1+str1
name1=os.path.abspath(completeName)
myfile = open(name1, 'w')

I want to save file a1.txt in my documents folder in my home directory.I get the following error using above code-

Traceback (most recent call last):
  File "filesave.py", line 8, in <module>
    myfile = open(name1, 'w')
FileNotFoundError: [Errno 2] No such file or directory: '/home/pulkit/Documents/Documents/Inbox/a1.txt'

Upvotes: 1

Views: 3149

Answers (4)

Ozan
Ozan

Reputation: 1074

This code shows you how to check the path exists and expand ~ to access home directory of the user running the script.

#!/usr/bin/python
import os
dpath=os.path.join(os.path.expanduser("~"),"Documents","Inbox")
if not os.path.exists(dpath):
    os.makedirs(dpath)
fpath=os.path.join(dpath,"a1.txt")
open(fpath,"w").write("what ever you want")

Upvotes: 3

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

See the error

FileNotFoundError: [Errno 2] No such file or directory: '/home/pulkit/Documents/Documents/Inbox/a1.txt'

Clearly, the path evaluated is:

/home/pulkit/Documents/Documents/Inbox/a1.txt

But you have,

/home/pulkit/Documents/Inbox/a1.txt

So, change file1="Documents/Inbox/" to file1="Inbox/"

Upvotes: 0

tripleee
tripleee

Reputation: 189487

os.path.abspath() does not know which directory you want the file to exist in -- it simply uses the current directory, which seems to have been $HOME/Documents when you got the backtrace.

Either

  1. always run the script from your home directory (untenable); or
  2. specify an explicit absolute path in the script; or
  3. change the logic so the script doesn't care where it's run -- commonly this is done by creating a file in the current directory always; or by simply printing to standard output, and let the user figure out what to do with the output.

Upvotes: 2

lukaz
lukaz

Reputation: 86

In your case omit the 'Documents/' from your variable file1 setting like:

file1="Inbox/"

Upvotes: 0

Related Questions