Python IDLE doesn't find text files unless I specify the path - python

In my Python books and also the Python Documents this code should be enough to open a file:
f = open("file.txt", "r")
But if I do this I will get an error message telling me file.txt doesn't exist. If I however use the whole path where file.txt is located it opens it:
f = open("C:/Users/Me/Python/file.txt", "r")
Is there an explanation for this?

In short - the immediate search path (the current working directory) is where Python will look... (so on Windows - possibly it'll assume C:\Pythonxy)
Yes, it depends on where Python/IDLE is executed... for it to use its search path:
>>> import os
>>> os.getcwd()
'/home/jon'
>>> open('testing.txt')
<open file 'testing.txt', mode 'r' at 0x7f86e140edb0>
And in a shell - changing directories... then launching Python/IDLE
jon#forseti:~$ cd /srv
jon#forseti:/srv$ idle
>>> import os
>>> os.getcwd()
'/srv'
>>> open('testing.txt')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
open('testing.txt')
IOError: [Errno 2] No such file or directory: 'testing.txt'

Related

Unable to open the file in txt in python

I have difficulty importing this file so that I can use it any help would greatly be appreciated.
import os
path = os.path.abspath(r'C:Users/kariwhite/Desktop/430 Python/week 4/cars.txt')
cars=open(path)
print (cars)
for line in cars:
values = line.split ()
print(values[0], 'has an MPG of', values[2], 'with', values[5])
# TODO: Split the line into a list of strings
# TODO: Print the sentence
# Close the file
cars.close()
FileNotFoundError Traceback (most recent call last)
Input In [14], in <cell line: 3>()
1 import os
2 path = os.path.abspath(r'C:Users/kariwhite/Desktop/430 Python/week 4/cars.txt')
----> 3 cars=open(path)
4 print (cars)
6 for line in cars:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/kariwhite/Desktop/430 Python/week 4/C:Users/kariwhite/Desktop/430 Python/week 4/cars.txt'
When reading files on python I'd highly recommend using the os.path module. It helps combine paths depending on which OS you're using. Assuming you're sure that the file exists, try the following:
import os
pwd = os.path.join("c:/", "Users", "kariwhite","Desktop","430 Python", "week 4", "cars.txt")
with open(pwd, "r") as file:
for line in file:
values = line.split()
#...
I'd highly recommend reading files using the syntax highlighted here too. with open() as file: ... is the best practice for file handling.
If you’re working in User/kariwhite/
Try
os.path.abspath(“Desktop/430 Python/week 4/cars.txt”)
You typically have to start the path from your current working directory if it’s moving forward from there and not in a sub directory.
Please note that the os.path.abspath() takes a path or file name as a parameter representing a file system path and returns a normalized version of the pathname path.
If the file actually exists in the specified directory (Users/kariwhite/Desktop/430 Python/week 4/cars.txt) and your working directory is Users/kariwhite/Desktop/430 Python/week 4 the below should work:
import os
path = os.path.abspath("cars.txt")
cars=open(path)
print (cars)
Also, if the file is in the current working directory you could use the relative path by opening the file directly:
import os
cars=open("cars.txt")
print (cars)

Creating new CSV files from inputs in different directory

I'm simply trying to alter a CSV file with Python.
When all the files were in the same dir, everything was fine.
Now that the input files are in a different dir than where the output files will be, everything blows up, apparently b/c the files do not exist?
I first found this:
open() in Python does not create a file if it doesn't exist
Then I learned to change to the directory, which helped me loop over the CSVs in the target dir:
Moving up one directory in Python
When I run the command:
python KWRG.py ../Weekly\ Reports\ -\ Inbound/Search\ Activity/ 8/9/2021
I will get:
Traceback (most recent call last): File "KWRG.py", line 15, in <module> with open(args.input, 'r') as in_file, open(args.output, 'w') as out_file: IsADirectoryError: [Errno 21] Is a directory: '../Weekly Reports - Inbound/Search Activity/'
Sorry If I'm missing the obvious here, but why is the file not being created in the directory that I'm pointing the script to (or at all for that matter)?
The code:
import csv
import argparse
import os
# Create a parser to take arguments
#...snip...
cur_dir = os.getcwd()
reports_dir = os.chdir(os.path.join(cur_dir, args.dir))
for csv_file in os.listdir(reports_dir):
# Shorthand the name of the file
#...snip...
# Open the in and out files
with open(csv_file, 'r') as in_file, open(f'{out_name}-Search-Activity-{args.date}.csv', 'w+') as out_file:
# Re-arrange CSV
# EOF
Your problem is with this line:
reports_dir = os.chdir(os.path.join(cur_dir, args.dir))
os.chdir() doesn't return anything, it just performs the operation requested - changing the current working directory. From an interactive session with the REPL:
>>> import os
>>> result = os.chdir("/Users/mattdmo/")
>>> result
>>>
For your purposes, all you need is
reports_dir = os.path.join(cur_dir, args.dir)
and you'll be all set.

CSV file creation error in python

I am getting some error while writing contents to csv file in python
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import csv
a = [['1/1/2013', '1/7/2013'], ['1/8/2013', '1/14/2013'], ['1/15/2013', '1/21/2013'], ['1/22/2013', '1/28/2013'], ['1/29/2013', '1/31/2013']]
f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)
Error
Traceback (most recent call last):
File "test.py", line 10, in <module>
f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
IOError: [Errno 2] No such file or directory: 'test_1/1/2013_.csv'
How to fix it and what is the error?
You have error message - just read it.
The file test_1/1/2013_.csv doesn't exist.
In the file name that you create - you use a[0][0] and in this case it result in 1/1/2013.
Probably this two signs '/' makes that you are looking for this file in bad directory.
Check where are this file (current directory - or in .test_1/1 directory.
It's probably due to the directory not existing - Python will create the file for you if it doesn't exist already, but it won't automatically create directories.
To ensure the path to a file exists you can combine os.makedirs and os.path.dirname.
file_name = 'test_'+str(a[0][0])+'_.csv'
# Get the directory the file resides in
directory = os.path.dirname(file_name)
# Create the directories
os.makedirs(directory)
# Open the file
f3 = open(file_name, 'at')
If the directories aren't desired you should replace the slashes in the dates with something else, perhaps a dash (-) instead.
file_name = 'test_' + str(a[0][0]).replace('/', '-') + '_.csv'

Python Permission Error when reading

import os
import rarfile
file = input("Password List Directory: ")
rarFile = input("Rar File: ")
passwordList = open(os.path.dirname(file+'.txt'),"r")
with this code I am getting the error:
Traceback (most recent call last):
File "C:\Users\Nick L\Desktop\Programming\PythonProgramming\RarCracker.py", line 7, in <module>
passwordList = open(os.path.dirname(file+'.txt'),"r")
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Nick L\\Desktop'
This is weird because I have full permission to this file as I can edit it and do whatever I want, and I am only trying to read it. Every other question I read on stackoverflow was regarding writing to a file and getting a permissions error.
You're trying to open a directory, not a file, because of the call to dirname on this line:
passwordList = open(os.path.dirname(file+'.txt'),"r")
To open the file instead of the directory containing it, you want something like:
passwordList = open(file + '.txt', 'r')
Or better yet, use the with construct to guarantee that the file is closed after you're done with it.
with open(file + '.txt', 'r') as passwordList:
# Use passwordList here.
...
# passwordList has now been closed for you.
On Linux, trying to open a directory raises an IsADirectoryError in Python 3.5, and an IOError in Python 3.1:
IsADirectoryError: [Errno 21] Is a directory: '/home/kjc/'
I don't have a Windows box to test this on, but according to Daoctor's comment, at least one version of Windows raises a PermissionError when you try to open a directory.
PS: I think you should either trust the user to enter the whole directory-and-file name him- or herself --- without you appending the '.txt' to it --- or you should ask for just the directory, and then append a default filename to it (like os.path.join(directory, 'passwords.txt')).
Either way, asking for a "directory" and then storing it in a variable named file is guaranteed to be confusing, so pick one or the other.
os.path.dirname() will return the Directory in which the file is present not the file path. For example if file.txt is in path= 'C:/Users/Desktop/file.txt' then os.path.dirname(path)wil return 'C:/Users/Desktop' as output, while the open() function expects a file path.
You can change the current working directory to file location and open the file directly.
os.chdir(<File Directory>)
open(<filename>,'r')
or
open(os.path.join(<fileDirectory>,<fileName>),'r')

Python - Open a file with a wildcard (%) directory path in Windows

In Python, I'm trying to open a file that gets saved to the %TEMP% directory. I've tried:
file = open("%TEMP%\file.txt")
and
file = open("%%TEMP%%\file.txt")
and
file = open("%TEMP%\\file.txt")
and
file = open("%%TEMP%%\\file.txt")
And always get (this one specifically for that last example):
IOError: [Errno 2] No such file or directory: '%%TEMP%%\\file.txt'
For sanity's sake, from Windows command prompt I do a type %TEMP%\file.txt and it prints out the file OK. Any help?
Use os.environ
import os
f = open(os.path.join(os.environ['TEMP'], 'file.txt'))
You can also use os.path.expandvars
import os
f = open(os.path.expandvars(r'%TEMP%\file.txt'))

Categories