-1

I am trying to find out if a txt file with 'newfile' name exists in a specified directory or not, if not create a new txt file

import os.path
if (os.path.exists("newfile.txt") == False):
    open("count.txt", "w")

but it does not work since I cannot access the current or specified director with this code.

M n
  • 1
  • 1
    What do you mean that you cannot access the current/specified directory – Wang Zerui Nov 21 '22 at 13:43
  • os.path is 'C:\\Program Files\\Python39\\lib\\ntpath.py', however my working directory where the txt file exist is another directory – M n Nov 21 '22 at 13:50
  • So what is your question? How to find the current working directory? `os.path` is a Python module – Tomerikoo Nov 21 '22 at 13:52
  • Does this answer your question? [Find the current directory and file's directory (duplicate)](https://stackoverflow.com/q/5137497/6045800) – Tomerikoo Nov 21 '22 at 13:53
  • I want to find a newfile.txt file in current directory – M n Nov 21 '22 at 13:54
  • Does this answer your question? [How can I make python script show an error when user inputs same file name with this piece of code?](https://stackoverflow.com/questions/74324942/how-can-i-make-python-script-show-an-error-when-user-inputs-same-file-name-with) – Arifa Chan Nov 21 '22 at 14:53

3 Answers3

1
import inspect
import os

module_path = inspect.getfile(inspect.currentframe())
module_dir = os.path.realpath(os.path.dirname(module_path))
os.chdir(module_dir) # set working directory to where file is

if not os.path.exists("C:\\absolute\\directory\\newfile.txt"):
    open("count.txt", "w")

You can replace the path with unix style directories.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Wang Zerui
  • 292
  • 1
  • 5
0

Solve 1:

import os.path

file = 'yourpath\file_to_check.txt'     # 예제 Textfile

if os.path.isfile(file):
  print("Yes. it is a file")
elif os.path.isdir(file):
  print("Yes. it is a directory")
elif os.path.exists(file):
  print("Something exist")
else :
  print("Nothing")

Solve 2:

from pathlib import Path

my_file = Path("your_path\file_to_check.txt") # This way only works in windows os
if my_file.is_file():
  print("Yes it is a file") 
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Evans Benedict
  • 276
  • 1
  • 1
  • 7
  • the problem is that os.path is not my current directory, or the directory that my txt file exist. @xlab – M n Nov 21 '22 at 13:48
  • If you add `yourpath` to the filename it should work as described here. Alternatively you can change your working directory with os.chdir(yourpath) and then operate with raw filenames. – Flow Nov 21 '22 at 14:17
0

You can use glob to locate the directory.

import glob

file_path = glob.glob('../your/file_directory/*')
if "count.txt" not in file_path:
    with open('../your/file_directory/count.txt', 'w') as f:
        f.write('Create new text file')

Jamiu S.
  • 5,257
  • 5
  • 12
  • 34