Issue with file path when deleting file in Python
Trying to write a small script in Python to delete files, but the os.remove function is having issues with the file path. Note if I comment out os.remove("C:\UsersThe UserDownloadstest.txt")
it runs fine and will print 'gone'. I don't understand why when assigning the path to the variable it works but os.remove doesn't like the same thing.
import os
import re
search ='test.txt'
path = "C:\UsersThe UserDownloads"
def find(search, path):
for root, dirs, files in os.walk(path):
if search in files:
return True
else:
return False
result = find(search, path)
if(result == False):
os.remove("C:\UsersThe UserDownloadstest.txt")
print('gone')
Here's the error message:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:UsersThe UserDownloadstest.txt'
python filepath delete-file
add a comment |
Trying to write a small script in Python to delete files, but the os.remove function is having issues with the file path. Note if I comment out os.remove("C:\UsersThe UserDownloadstest.txt")
it runs fine and will print 'gone'. I don't understand why when assigning the path to the variable it works but os.remove doesn't like the same thing.
import os
import re
search ='test.txt'
path = "C:\UsersThe UserDownloads"
def find(search, path):
for root, dirs, files in os.walk(path):
if search in files:
return True
else:
return False
result = find(search, path)
if(result == False):
os.remove("C:\UsersThe UserDownloadstest.txt")
print('gone')
Here's the error message:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:UsersThe UserDownloadstest.txt'
python filepath delete-file
1
You should returnTrue
orFalse
instead of'yes'
and'no'
.
– Jonah Bishop
Nov 26 '18 at 2:06
First of all, please include your actual code. There's a typo infind()
that indicates this is not the exact code you are running. Also, please fix your indentation, as it's not clear what you're code is actually doing. Once you've done that, tell us what issuesos.remove
is having, and please include any errors in your question, in full.
– Cyphase
Nov 26 '18 at 2:10
Regardless of my previous comment,find()
is not going to work generally because, at best, it will tell you ifsearch
is a file somewhere underpath
, not whether it's in the top-levelpath
directory.
– Cyphase
Nov 26 '18 at 2:17
Can you be more specific than "the os.remove function is having issues"? What issues is it having? Is it raising an exception? If so, give us the full traceback (you can format it like code). If the issues are something else (e.g. it's not doing what you expect), you need to explain what it is doing, and what you expect it to do instead.
– Blckknght
Nov 26 '18 at 2:27
I've cleaned it up and changed to true/false. I also added the error message.
– WeVie
Nov 26 '18 at 3:35
add a comment |
Trying to write a small script in Python to delete files, but the os.remove function is having issues with the file path. Note if I comment out os.remove("C:\UsersThe UserDownloadstest.txt")
it runs fine and will print 'gone'. I don't understand why when assigning the path to the variable it works but os.remove doesn't like the same thing.
import os
import re
search ='test.txt'
path = "C:\UsersThe UserDownloads"
def find(search, path):
for root, dirs, files in os.walk(path):
if search in files:
return True
else:
return False
result = find(search, path)
if(result == False):
os.remove("C:\UsersThe UserDownloadstest.txt")
print('gone')
Here's the error message:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:UsersThe UserDownloadstest.txt'
python filepath delete-file
Trying to write a small script in Python to delete files, but the os.remove function is having issues with the file path. Note if I comment out os.remove("C:\UsersThe UserDownloadstest.txt")
it runs fine and will print 'gone'. I don't understand why when assigning the path to the variable it works but os.remove doesn't like the same thing.
import os
import re
search ='test.txt'
path = "C:\UsersThe UserDownloads"
def find(search, path):
for root, dirs, files in os.walk(path):
if search in files:
return True
else:
return False
result = find(search, path)
if(result == False):
os.remove("C:\UsersThe UserDownloadstest.txt")
print('gone')
Here's the error message:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:UsersThe UserDownloadstest.txt'
python filepath delete-file
python filepath delete-file
edited Nov 26 '18 at 3:28
WeVie
asked Nov 26 '18 at 2:02
WeVieWeVie
198418
198418
1
You should returnTrue
orFalse
instead of'yes'
and'no'
.
– Jonah Bishop
Nov 26 '18 at 2:06
First of all, please include your actual code. There's a typo infind()
that indicates this is not the exact code you are running. Also, please fix your indentation, as it's not clear what you're code is actually doing. Once you've done that, tell us what issuesos.remove
is having, and please include any errors in your question, in full.
– Cyphase
Nov 26 '18 at 2:10
Regardless of my previous comment,find()
is not going to work generally because, at best, it will tell you ifsearch
is a file somewhere underpath
, not whether it's in the top-levelpath
directory.
– Cyphase
Nov 26 '18 at 2:17
Can you be more specific than "the os.remove function is having issues"? What issues is it having? Is it raising an exception? If so, give us the full traceback (you can format it like code). If the issues are something else (e.g. it's not doing what you expect), you need to explain what it is doing, and what you expect it to do instead.
– Blckknght
Nov 26 '18 at 2:27
I've cleaned it up and changed to true/false. I also added the error message.
– WeVie
Nov 26 '18 at 3:35
add a comment |
1
You should returnTrue
orFalse
instead of'yes'
and'no'
.
– Jonah Bishop
Nov 26 '18 at 2:06
First of all, please include your actual code. There's a typo infind()
that indicates this is not the exact code you are running. Also, please fix your indentation, as it's not clear what you're code is actually doing. Once you've done that, tell us what issuesos.remove
is having, and please include any errors in your question, in full.
– Cyphase
Nov 26 '18 at 2:10
Regardless of my previous comment,find()
is not going to work generally because, at best, it will tell you ifsearch
is a file somewhere underpath
, not whether it's in the top-levelpath
directory.
– Cyphase
Nov 26 '18 at 2:17
Can you be more specific than "the os.remove function is having issues"? What issues is it having? Is it raising an exception? If so, give us the full traceback (you can format it like code). If the issues are something else (e.g. it's not doing what you expect), you need to explain what it is doing, and what you expect it to do instead.
– Blckknght
Nov 26 '18 at 2:27
I've cleaned it up and changed to true/false. I also added the error message.
– WeVie
Nov 26 '18 at 3:35
1
1
You should return
True
or False
instead of 'yes'
and 'no'
.– Jonah Bishop
Nov 26 '18 at 2:06
You should return
True
or False
instead of 'yes'
and 'no'
.– Jonah Bishop
Nov 26 '18 at 2:06
First of all, please include your actual code. There's a typo in
find()
that indicates this is not the exact code you are running. Also, please fix your indentation, as it's not clear what you're code is actually doing. Once you've done that, tell us what issues os.remove
is having, and please include any errors in your question, in full.– Cyphase
Nov 26 '18 at 2:10
First of all, please include your actual code. There's a typo in
find()
that indicates this is not the exact code you are running. Also, please fix your indentation, as it's not clear what you're code is actually doing. Once you've done that, tell us what issues os.remove
is having, and please include any errors in your question, in full.– Cyphase
Nov 26 '18 at 2:10
Regardless of my previous comment,
find()
is not going to work generally because, at best, it will tell you if search
is a file somewhere under path
, not whether it's in the top-level path
directory.– Cyphase
Nov 26 '18 at 2:17
Regardless of my previous comment,
find()
is not going to work generally because, at best, it will tell you if search
is a file somewhere under path
, not whether it's in the top-level path
directory.– Cyphase
Nov 26 '18 at 2:17
Can you be more specific than "the os.remove function is having issues"? What issues is it having? Is it raising an exception? If so, give us the full traceback (you can format it like code). If the issues are something else (e.g. it's not doing what you expect), you need to explain what it is doing, and what you expect it to do instead.
– Blckknght
Nov 26 '18 at 2:27
Can you be more specific than "the os.remove function is having issues"? What issues is it having? Is it raising an exception? If so, give us the full traceback (you can format it like code). If the issues are something else (e.g. it's not doing what you expect), you need to explain what it is doing, and what you expect it to do instead.
– Blckknght
Nov 26 '18 at 2:27
I've cleaned it up and changed to true/false. I also added the error message.
– WeVie
Nov 26 '18 at 3:35
I've cleaned it up and changed to true/false. I also added the error message.
– WeVie
Nov 26 '18 at 3:35
add a comment |
1 Answer
1
active
oldest
votes
I think you should just return the full path of the file to delete, and if the path is not None
, then call os.remove()
. In your code, you check that search
exists in files
, but files
is a list, and you need to go through and get the matching file to determine its current directory. Then you can get the full path using root
, and use that later for deletion.
Demo:
from os import environ
from os import walk
from os import remove
from os.path import join
def find(search, path):
for root, _, files in walk(path):
# Go through each file
for file in files:
# Check if the file matches the search
if file == search:
# return full path
return join(root, file)
# Get path if any
result = find(search="test.txt", path=join(environ["USERPROFILE"], "Downloads"))
# Only delete file if not None
if result:
remove(result)
print('Deleted', result)
You can can also use next()
here to make find()
shorter:
def find(search, path):
for root, _, files in walk(path):
return next((join(root, file) for file in files if file == search), None)
Note: You can use os.path.join(os.environ['USERPROFILE'], 'Downloads')
instead of hardcoding C:\UsersThe UserDownloads
.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473893%2fissue-with-file-path-when-deleting-file-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I think you should just return the full path of the file to delete, and if the path is not None
, then call os.remove()
. In your code, you check that search
exists in files
, but files
is a list, and you need to go through and get the matching file to determine its current directory. Then you can get the full path using root
, and use that later for deletion.
Demo:
from os import environ
from os import walk
from os import remove
from os.path import join
def find(search, path):
for root, _, files in walk(path):
# Go through each file
for file in files:
# Check if the file matches the search
if file == search:
# return full path
return join(root, file)
# Get path if any
result = find(search="test.txt", path=join(environ["USERPROFILE"], "Downloads"))
# Only delete file if not None
if result:
remove(result)
print('Deleted', result)
You can can also use next()
here to make find()
shorter:
def find(search, path):
for root, _, files in walk(path):
return next((join(root, file) for file in files if file == search), None)
Note: You can use os.path.join(os.environ['USERPROFILE'], 'Downloads')
instead of hardcoding C:\UsersThe UserDownloads
.
add a comment |
I think you should just return the full path of the file to delete, and if the path is not None
, then call os.remove()
. In your code, you check that search
exists in files
, but files
is a list, and you need to go through and get the matching file to determine its current directory. Then you can get the full path using root
, and use that later for deletion.
Demo:
from os import environ
from os import walk
from os import remove
from os.path import join
def find(search, path):
for root, _, files in walk(path):
# Go through each file
for file in files:
# Check if the file matches the search
if file == search:
# return full path
return join(root, file)
# Get path if any
result = find(search="test.txt", path=join(environ["USERPROFILE"], "Downloads"))
# Only delete file if not None
if result:
remove(result)
print('Deleted', result)
You can can also use next()
here to make find()
shorter:
def find(search, path):
for root, _, files in walk(path):
return next((join(root, file) for file in files if file == search), None)
Note: You can use os.path.join(os.environ['USERPROFILE'], 'Downloads')
instead of hardcoding C:\UsersThe UserDownloads
.
add a comment |
I think you should just return the full path of the file to delete, and if the path is not None
, then call os.remove()
. In your code, you check that search
exists in files
, but files
is a list, and you need to go through and get the matching file to determine its current directory. Then you can get the full path using root
, and use that later for deletion.
Demo:
from os import environ
from os import walk
from os import remove
from os.path import join
def find(search, path):
for root, _, files in walk(path):
# Go through each file
for file in files:
# Check if the file matches the search
if file == search:
# return full path
return join(root, file)
# Get path if any
result = find(search="test.txt", path=join(environ["USERPROFILE"], "Downloads"))
# Only delete file if not None
if result:
remove(result)
print('Deleted', result)
You can can also use next()
here to make find()
shorter:
def find(search, path):
for root, _, files in walk(path):
return next((join(root, file) for file in files if file == search), None)
Note: You can use os.path.join(os.environ['USERPROFILE'], 'Downloads')
instead of hardcoding C:\UsersThe UserDownloads
.
I think you should just return the full path of the file to delete, and if the path is not None
, then call os.remove()
. In your code, you check that search
exists in files
, but files
is a list, and you need to go through and get the matching file to determine its current directory. Then you can get the full path using root
, and use that later for deletion.
Demo:
from os import environ
from os import walk
from os import remove
from os.path import join
def find(search, path):
for root, _, files in walk(path):
# Go through each file
for file in files:
# Check if the file matches the search
if file == search:
# return full path
return join(root, file)
# Get path if any
result = find(search="test.txt", path=join(environ["USERPROFILE"], "Downloads"))
# Only delete file if not None
if result:
remove(result)
print('Deleted', result)
You can can also use next()
here to make find()
shorter:
def find(search, path):
for root, _, files in walk(path):
return next((join(root, file) for file in files if file == search), None)
Note: You can use os.path.join(os.environ['USERPROFILE'], 'Downloads')
instead of hardcoding C:\UsersThe UserDownloads
.
edited Nov 26 '18 at 3:36
answered Nov 26 '18 at 2:33
RoadRunnerRoadRunner
11.3k31441
11.3k31441
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473893%2fissue-with-file-path-when-deleting-file-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
You should return
True
orFalse
instead of'yes'
and'no'
.– Jonah Bishop
Nov 26 '18 at 2:06
First of all, please include your actual code. There's a typo in
find()
that indicates this is not the exact code you are running. Also, please fix your indentation, as it's not clear what you're code is actually doing. Once you've done that, tell us what issuesos.remove
is having, and please include any errors in your question, in full.– Cyphase
Nov 26 '18 at 2:10
Regardless of my previous comment,
find()
is not going to work generally because, at best, it will tell you ifsearch
is a file somewhere underpath
, not whether it's in the top-levelpath
directory.– Cyphase
Nov 26 '18 at 2:17
Can you be more specific than "the os.remove function is having issues"? What issues is it having? Is it raising an exception? If so, give us the full traceback (you can format it like code). If the issues are something else (e.g. it's not doing what you expect), you need to explain what it is doing, and what you expect it to do instead.
– Blckknght
Nov 26 '18 at 2:27
I've cleaned it up and changed to true/false. I also added the error message.
– WeVie
Nov 26 '18 at 3:35