How can I check if a file exists in python? [duplicate] - python

This question already has answers here:
How do I check whether a file exists without exceptions?
(40 answers)
Closed 3 years ago.
I am trying to make a python script to make entries in an excel file that will have daily entries.
I want to check if a file exists then open it.
if the file does not exist then I want to make a new file.
if have used os path exists to see if the file is present
workbook_status = os.path.exists("/log/"+workbookname+".xlxs")
if workbook_status = "True":
# i want to open the file
Else:
#i want to create a new file

I think you just need that
try:
f = open('myfile.xlxs')
f.close()
except FileNotFoundError:
print('File does not exist')
If you want to check with if-else than go for this:
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists

import os
import os.path
PATH='./file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print "File exists and is readable/there"
else:
f = open('myfile.txt')
f.close()

You should use following statement:
if os.path.isfile("/{file}.{ext}".format(file=workbookname, ext=xlxs)):
# Open file

Related

os.path.exists() say False [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I'm trying to make a code that downloads a file if it doesn't exist
import requests
from os.path import exists
def downloadfile(url):
if exists('file.txt')==False:
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
return
downloadfile('https://url.to/file.txt')
my folder:
testfolder
test.py
file.txt
...
in idle
from os.path import exists
exists('file.txt') # True
in test.py, exists() say False
how fix it?
If it reads false, it's probably looking in the wrong place. Use the following to see where the code is looking in (file directory):
import os
print(os.getcwd())
Then you can either put the file you're looking for in that directory or change the code to the file directory which the file is currently in.

Python: File Not Found Error. No such file or directory named [duplicate]

This question already has answers here:
Why am I getting a FileNotFoundError? [duplicate]
(8 answers)
Closed 9 months ago.
I have to read a simple file named 'highscore.txt' in my slakes.py file.
Both are located in same folder.
But idk why I am getting file not found error
Code:
with open('highscore.txt', 'r') as f:
high_score = f.read()
This part of code check if file is exist. If not - create this empty file and read this file.
I recommend using the full path to your file like /home/user/folde/subfolder/file.txt
I hope this helps you.
from subprocess import call as subprocess_call
from os.path import isfile as file_exist
file = "/path/to/your/file"
if not file_exist(file):
# create file if exist
subprocess_call(["touch", file])
subprocess_call(["chmod", "777", file])
with open(file, "r") as f:
high_score = f.read()
Try using module named csv
The following code is a basic code to read a file:
import csv
with open('file directory') as F:
reader = csc.reader(F)
for row in reader:
print (rows)
You can use any variables
Please check whether the folder where the VS Code terminal is currently located is the parent folder of the python file being executed.
Solution:
You could use the command "cd folder_name" in the terminal to go to the parent folder of the python file:
Or use the following settings in the settings file "settings.json":
"python.terminal.executeInFileDir": true,
It will automatically go to the parent folder of the current file before executing the run command:

File not found Python [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I have tried to get my program to open but it keeps saying FileNotFound
def main():
with open("number.txt") as f:
nums=[int(x) for x in f.read().split()]
print(nums)
for nums in nums:
total += int(nums)
print(total)
print(len(nums))
return total / len(nums)
main()
Is number.txt in your working directory? If not you'd have to specify the path to that file so python knows where to look
Python will look for "number.txt" in your current directory which by default is the same folder that your code started running in. You can get the current directory by using os.getcwd() and if that for some reason is not what you expect, you can also get the directory to the folder that your code is running in by doing current_directory = os.path.dirname(os.path.realpath(__file__)).
The following code should always work, if you want your "number.txt" to be in the same folder as your code.
import os.path
def main():
current_directory = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(current_directory, "number.txt")
# Optionally use this to create the file if it does not exist
if not os.path.exists(filepath):
open(filepath, 'w').close()
with open( filepath ) as f:
...

how to detect file if exist in python [duplicate]

This question already has answers here:
How do I check whether a file exists without exceptions?
(40 answers)
Closed 3 years ago.
how can i detect if a specifics files exist in directory ?
example:
i want to detect if (.txt) files exist in directory (dir)
i tried with this :
import os.path
from os import path
def main():
print ("file exist:"+str(path.exists('guru99.txt')))
print ("File exists:" + str(path.exists('career.guru99.txt')))
print ("directory exists:" + str(path.exists('myDirectory')))
if __name__== "__main__":
main()
but all this functions you must to insert the complete file name with format(.txt)
Thank you !
from glob import glob
files = glob('*.txt')
print(len(files)) # will return the number of .txt files in the dir
print(files) # will return all the .txt files in the dir
to check if a specific file exists:
import os
os.path.exists(path_to_file)
will return True if it exists, False if not
to check if ANY .txt files exist:
import glob
if glob.glob(path_to_files_'*.txt'):
print('exists')
else:
print('doesnt')

how to check if a file is a directory or regular file in python? [duplicate]

This question already has answers here:
How to identify whether a file is normal file or directory
(7 answers)
Closed 3 years ago.
How do you check if a path is a directory or file in python?
os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory?
os.path.isdir("bob")
use os.path.isdir(path)
more info here http://docs.python.org/library/os.path.html
Many of the Python directory functions are in the os.path module.
import os
os.path.isdir(d)
An educational example from the stat documentation:
import os, sys
from stat import *
def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
# It's a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
def visitfile(file):
print 'visiting', file
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)

Categories