Python filename if statement not working - python

I have a python script that I need to run from the windows command line. The line
for filename in os.listdir(os.getcwd() + "\\sampdirectory1\\sampdirectory2"):
if filename.startswith("sample.csv"):
os.remove("sample.csv")
keeps giving me the error
The system cannot find the file specified 'sample.csv'
Well the file doesn't exist yet, it's created in the script for the first time then edited by the script every time after that. What I don't understand is why it's trying the do os.remove on sample.csv, when the if statement should fail, meaning the remove shouldn't be reached.

You can't delete it while holding on to it because "On Windows, attempting to remove a file that is in use causes an exception to be raised"
https://docs.python.org/2/library/os.html#os.remove

There are 2 things to notice here:
first: the folder/destination are different. you should be using
os.remove(os.getcwd() + "\sampdirectory1\sampdirectory2" + "sample.csv")
second: a more elegant solution would be
try:
os.remove(os.getcwd() + "\\sampdirectory1\\sampdirectory2" + "sample.csv")
except:
print ('no such file/directory')
pass

There might be a file .\sampdirectory1\sampdirectory2\sample.csv, so the condition is valid. But you're trying to delete a file .\sample.csv (sample.csv in current directory) that doesn't exist and you're getting the error.
Moreover, there might be a file .\sampdirectory1\sampdirectory2\sample.csvSOMETHING, so the condition is still valid and you're getting the error.

You need to do os.remove(filename) instead of os.remove("sample.csv")
Because at first sample.csv is not the file that you are checking if it exists before removing. And even the filename is sample.csv you need to precise to full path of the file.
And as you are iterating over listing the directory files you don't need to check if the file exists.
So if you want to remove files whose names start with sample.csv, the code should be as below:
for filename in os.listdir(os.getcwd() + "\\sampdirectory1\\sampdirectory2"):
if filename.startswith("sample.csv"):
os.remove(filename)
But if you want to remove only sample.csv, then you don't need any loop. Just do
filename = os.path.join(os.getcwd(), "sampdirectory1\\sampdirectory2\\sample.csv")
if os.path.exists(filename):
os.remove(filename)

Related

trying to delete file but its not working

I tried to delete a file but it just does the else statement even though the file exists.
I also tried to delete other files, but I got same result.
Here is the code:
def deletees():
if os.path.exists("C:\X-Folder\plugins\autorun"):
shutil.rmtree("C:\X-Folder\plugins\autorun")
else:
print("error: does not exists")
deletees()
If you are trying to remove a single file:
os.remove(r"C:\X-Folder\plugins\autorun")
# or
os.remove("C:\\X-Folder\\plugins\\autorun")
If you are trying to remove a directory or directory tree:
shutil.rmtree(r"C:\X-Folder\plugins\autorun")
# or
shutil.rmtree("C:\\X-Folder\\plugins\\autorun")
Notice that a raw(r) string is used so that \ characters aren't escaped.
So your specific example would look like this:
Uncomment the line that is most appropriate for your situation.
def deletees():
if os.path.exists("C:\\X-Folder\\plugins\\autorun"):
shutil.rmtree("C:\\X-Folder\\plugins\\autorun") # uncomment me for a directory
# os.remove("C:\\X-Folder\\plugins\\autorun") # uncomment me for a file
else:
print("error: does not exists")
deletees()
Finally there is also os.rmdir and os.removedirs but they only work on empty directories and I would not recommend using either of them.

Confusing problem >> FileNotFoundError: [Errno 2] No such file or directory:

This problem puzzled me.
Maybe the problem is in the code, I hope you take a look
with open(training_images_labels_path,'r') as file:
lines = file.readlines()
He says that the file does not exist
FileNotFoundError: [Errno 2] No such file or directory: '\\Desktop\\project\\data\\generated\\training_images_labels.txt'
Though the file exists
I need solutions
If it says that the file does not exist though the file exists, it means the path has been not given properly. Try giving the path correctly.
Method 1:
Giving correct path 'C:\\Users\\Public\\Desktop\\project\\data\\generated\\training_images_labels.txt' or
'C:\\Users\\<insert your username>\\Desktop\\project\\data\\generated\\training_images_labels.txt' is your path if I guess correctly
Method 2:
Using os module ( Recommended )
mydir = 'C:/Users/Public/Desktop/project/data/generated'
myfile = 'training_images_labels.txt'
training_images_labels_path = os.path.join(mydir, myfile)
with open(training_images_labels_path,'r') as file:
lines = file.readlines()
Method 3:
You can also try changing the working directory to the location where your data is present. ie Desktop>project>data>generated here and open the file with file name. ie
with open('training_images_labels.txt','r') as file:
lines = file.readlines()
I had the same problem with importing an excel file, which of course exists in the same directory with my .py file. The chosen solution above did not help me, and actually I didn't understand those three methods, as I am working on mac OS.
This method worked for me: in Spyder, I usually run the file by pressing the keys "Shift + Enter", which in this case made the problem. So, my solution was, to press on the "Run file" button (or the fn+F5 key) instead.
Maybe someone wants to explain the difference.
Looks like its a windows path you are working and i believe path really thrown in the error is wrong when compared to the actual where the txt file resides.. just cross check once, if that's the case try to pass the correct path in to the variable "training_images_labels_path"
Can you tell how you created this path.Some advise.
use path separator library to generate path to avoid this error.
training_images_labels_path
further try to navigate parent directory using python and print pth.may be some new line or linux/windwos convereted path or other special character in path. navigating parent directory and listing will solve
if still not solve try to navigatep parent-parent dir and print path
try hard
Watch your path if its correct or not. I had the same problem and it turned out i didnt had the good path set

Checking if file in use (by other process) by trying to rename it to same name (in Python on Windows)

I want to detect if a file is being written to by another process before I start to read the contents of that file.
This is on Windows and I am using Python (2.7.x).
(By the way, the Python script is providing a service where it acts on files that are placed in a specified folder. It acts on the files as soon as they are detected and it deletes the files after having acted on them. So I don't want to start acting on a file that is only partially written.)
I have found empirically that trying to rename the file to the same name will fail if the file is being written to (by another process) and will succeed (as a null-op) if the file is not in use by another process.
Something like this:
def isFileInUse(filePath):
try:
os.rename(filePath, filePath)
return False
except Exception:
return True
I haven't seen anything documented about the behaviour of os.rename when source and destination are the same.
Does anyone know of something that might go wrong with what I am doing above?
I emphasize that I am looking for a solution that works in Windows,
and I note that os.access doesn't seem to work - even with os.W_OK it returns True even if the file is being written by another process.
One thing that is nice about the above solution (renaming to the same name) is that it is atomic - which is not true if I try to rename to a temp name, then rename back to the original name.
Since you only want to read the file - why not just try to do it? Since this is the operation you are trying to do:
try:
with open("file.txt", "r") as handle:
content = handle.read()
except IOError as msg:
pass # error handling
This will try to read the content, and fail if the file is locked, or unreadable.
I see no reason to check if the file is locked if you just want to read from it - just try reading and see if that throws an exception.

Saving data in Python without a text file?

I have a python program that just needs to save one line of text (a path to a specific folder on the computer).
I've got it working to store it in a text file and read from it; however, I'd much prefer a solution where the python file is the only one.
And so, I ask: is there any way to save text in a python program even after its closed, without any new files being created?
EDIT: I'm using py2exe to make the program an .exe file afterwards: maybe the file could be stored in there, and so it's as though there is no text file?
You can save the file name in the Python script and modify it in the script itself, if you like. For example:
import re,sys
savefile = "widget.txt"
x = input("Save file name?:")
lines = list(open(sys.argv[0]))
out = open(sys.argv[0],"w")
for line in lines:
if re.match("^savefile",line):
line = 'savefile = "' + x + '"\n'
out.write(line)
This script reads itself into a list then opens itself again for writing and amends the line in which savefile is set. Each time the script is run, the change to the value of savefile will be persistent.
I wouldn't necessarily recommend this sort of self-modifying code as good practice, but I think this may be what you're looking for.
Seems like what you want to do would better be solved using the Windows Registry - I am assuming that since you mentioned you'll be creating an exe from your script.
This following snippet tries to read a string from the registry and if it doesn't find it (such as when the program is started for the first time) it will create this string. No files, no mess... except that there will be a registry entry lying around. If you remove the software from the computer, you should also remove the key from the registry. Also be sure to change the MyCompany and MyProgram and My String designators to something more meaningful.
See the Python _winreg API for details.
import _winreg as wr
key_location = r'Software\MyCompany\MyProgram'
try:
key = wr.OpenKey(wr.HKEY_CURRENT_USER, key_location, 0, wr.KEY_ALL_ACCESS)
value = wr.QueryValueEx(key, 'My String')
print('Found value:', value)
except:
print('Creating value.')
key = wr.CreateKey(wr.HKEY_CURRENT_USER, key_location)
wr.SetValueEx(key, 'My String', 0, wr.REG_SZ, 'This is what I want to save!')
wr.CloseKey(key)
Note that the _winreg module is called winreg in Python 3.
Why don't you just put it at the beginning of the code. E.g. start your code:
import ... #import statements should always go first
path = 'what you want to save'
And now you have path saved as a string

Safe way to read directory in Python

try:
directoryListing = os.listdir(inputDirectory)
#other code goes here, it iterates through the list of files in the directory
except WindowsError as winErr:
print("Directory error: " + str((winErr)))
This works fine, and I have tested that it doesnt choke and die when the directory doesn't exist, but I was reading in a Python book that I should be using "with" when opening files. Is there a preferred way to do what I am doing?
You are perfectly fine. The os.listdir function does not open files, so ultimately you are alright. You would use the with statement when reading a text file or similar.
an example of a with statement:
with open('yourtextfile.txt') as file: #this is like file=open('yourtextfile.txt')
lines=file.readlines() #read all the lines in the file
#when the code executed in the with statement is done, the file is automatically closed, which is why most people use this (no need for .close()).
What you are doing is fine. With is indeed the preferred way for opening files, but listdir is perfectly acceptable for just reading the directory.

Categories

Resources