This question already has answers here:
Python raising FileNotFoundError for file name returned by os.listdir
(3 answers)
Closed 4 years ago.
import os
import time
torrent_folder = os.listdir(r'C:\users\chris\desktop\torrents')
for files in torrent_folder:
if files.endswith(".torrent"):
print(files + time.ctime(os.path.getatime(files)))
I am getting a file not found error when running this script.
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'TORRENT NAME.torrent'
everything works fine until time.ctime(os.path.getatime(files)
is added into the mix.
I would like the script to display 'torrent name' 'date last modified'
for each file in the folder.
Why is the error referencing a file, by name that it says it is unable to find and how can i fix this?
Your files variable is the file name only, not the complete path. Hence it will be looking for it in your current working directory, not where listdir found it.
The following code will use the full path name:
import os
import time
folder = r'C:\users\chris\desktop\torrent'
files = os.listdir(folder)
for file in files:
if file.endswith(".torrent"):
print(file + " " + time.ctime(os.path.getatime(os.path.join(folder,file))))
The os.path.join() combines folder and file to give you a full path specification. For example, os.path.join("/temp","junk.txt") would give you /temp/junk.txt (under UNIX).
Then it uses that in exactly the same way you tried to use just the file variable, getting the last access time and formatting it in a readable manner.
It require absolute path.
os.path.getatime(path)
Return the time of last access of path.
so, open('xxx.torrent') will not work.
Instead, use open('C:\users\chris\desktop\torrents\xxx.torrent')
import os
import time
torrent_folder = os.listdir(r'C:\users\chris\desktop\torrents')
for files in torrent_folder:
if files.endswith(".torrent"):
filepath = os.path.join('C:\users\chris\desktop\torrents',files)
print(files + time.ctime(os.path.getatime(filepath)))
Related
This question already has answers here:
How to reliably open a file in the same directory as the currently running script
(9 answers)
Closed last year.
I am stuck to this weirdly small problem for like 3 hours and i just can't find the fix of it. Here look at the problem I'm trying to read a .txt file(greetings.txt) which contains a simple message and both- the .txt file and the program to read the file (readingfile.py) are inside the same folder, but still when i try to run the program which should return the text inside the .txt file , instead , it's throwing an error FileNotFoundError: [Errno 2] No such file or directory: 'greetings.txt' If you think you familiar with this issue please help.
The code is written below and i will be also attaching an image please check that as well.Go through this link to view the image
with open('greetings.txt') as file:
content = file.read()
print(content)
Your corrent folder is not the parent folder of the script, which is coincidentally also where your greetings.txt file is located.
To fix that, use __file__ to get the absolute path of the executing script, and then join with the parent path to get the absolute path of the text file.
For instance:
import os
path_to_file = os.path.join(os.path.dirname(__file__), 'greetings.txt')
with open(path_to_file) as file:
...
Alternatively, in Python 3.x, the above code can be simplified even further by relying on pathlib module:
from pathlib import Path
content = (Path(__file__).parent / 'greetings.txt').read_text()
This question already has answers here:
Find a file in python
(9 answers)
Closed 1 year ago.
file searching
how would imake a program that would check if my pc had a file with a certain name no matter what type the file is and then print yes or no.
For example i would put in a file name then it would print if i had it or not. ive tried similar things but they didnt work for me.
You can use the os module for this.
import os
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name) # or you could print 'found' or something
This will find the first match. If it exists, it will return the file path, otherwise it returns None. Note that it is case sensitive.
This was taken from this answer.
you can also use Pathlib module. The code written using Pathlib will work on any OS.
#pathlib will work on any OS (linux,windows,macOS)
from pathlib import Path
# define the search Path here '.' means current working directory. you can specify other path like Path('/User/<user_name>')
search_path = Path('.')
# define the file name to be searched here.
file_name = 'test.txt'
#iteratively search glob() will return generator object. It'll be a lot faster.
for file in search_path.glob('**/*'):
if file.name == file_name:
print(f'file found = {file.absolute()}') #print the file path if file is found
break
This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
Opened VS code thru Anaconda3 and when trying to read a csv using pandas
df = pd.read_csv('file.csv')
My file.csv exists in same directory as my panda.py file but i receive a
FileNotFoundError: [Errno 2] File b'file.csv' does not exist: b'file.csv'
I can physically see the file in the same directory but my terminal says its not.
Why is this happening and how can i fix it?
${cwd} - the task runner's current working directory on startup.
The default setting of 'cwd' is the "${workspaceFolder}". In VSCode, the relative path depends on the setting parameter 'cwd', unless you use an absolute path. It doesn't care the relative path to your python file, it just cares the relative path to 'cwd'.
So you have two solutions to solve this problem:
First One:
Use the absolute path as you had tried and worked:
df = pd.read_csv(r'C:\Users\First Last\Documents\StatPython\file.csv')
or
df = pd.read_csv('C:\Users\irst Last\Documents\StatPython\file.csv')
Second One:
Take the path relative to default ${cwd}:
df = pd.read_csv('[the path of cwd][some paths]\file.csv')
In this case, seems like you haven't created a project of 'StatPython'. If it is your project name and opened by VSCode your code should be worked.
this is because you are using a DataFrame to read the csv file while the DataFrame module cannot do that.
Instead you can try using pandas to do the same operation by importing it using import pandas as pd and to read the file use pd.read_csv('filename.csv')
Still not sure why my code in question did not work, but this ended up working.
df = pd.read_csv(r'C:\Users\First Last\Documents\StatPython\file.csv')
Not only did i need the full path but an "r" before it.
This question already has answers here:
Find the current directory and file's directory [duplicate]
(13 answers)
Closed 3 years ago.
For a project I am working on in python, I need to be able to view what directory a file is in. Essentially it is a find function, however I have no idea how to do this using python.
I have tried searching on google, but only found how to view files inside a directory. I want to view directory using a file name.
To summarise: I don't know the directory, and want to find it using the file inside it.
Thanks.
In Python, the common standard libraries for working with your local files are:
os.path
os
pathlib
If you have a path to a file & want it's directory, then we need to extract it:
>>> import os
>>> filepath = '/Users/guest/Desktop/blogpost.md'
>>> os.path.dirname(filepath) # Returns a string of the directory name
'/Users/guest/Desktop'
If you want the directory of your script, the keyword you need to search for is the "current working directory":
>>> import os
>>> os.getcwd() # returns a string of the current working directory
'/Users/guest/Desktop'
Also check out this SO post for more common operations you'll likely need.
Here's what I did:
import os
print(os.getcwd())
I am playing around with some python scripts and I ran into a problem with the script I'm writing. It's supposed to find all the files in a folder that meets the criteria and then delete it. However, it finds the files, but at the time of deleting the file, it says that the file is not found.
This is my code:
import os
for filename in os.listdir('C:\\New folder\\'):
if filename.endswith(".rdp"):
os.unlink(filename)
And this is the error I get after running it:
FileNotFoundError: [WinError 2] The system cannot find the file specified:
Can somebody assist with this?
os.unlink takes the path to the file, not only its filename. Try pre-pending your filename with the dirname. Like this
import os
dirname = 'C:\\New folder\\'
for filename in os.listdir(dirname):
if filename.endswith(".rdp"):
# Add your "dirname" to the file path
os.unlink(dirname + filename)
You could alternatively use os.walk, however it might go deeper than you want:
import os
for root, sub, file in os.walk("/media/"):
if file.endswith(".rdp"):
os.unlink(f'{root}/{file}')