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.
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')
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.
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.