Unable to open the file in txt in python - 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)

Related

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.

How to get the path of the file calling a function of an imported file from within the imported file

I'm trying to make parsing CSVs a little easier on me later down the road so I've created a small file to allow me to run parse_csv.toList('data.csv') and return a list to my script. Here is what the parse_csv.py imported file looks like:
parse_csv.py
import csv
def toList(file_location_name):
result_list = []
with open(file_location_name) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
result_list.append(row)
return result_list
This is how I'm calling it in my scripts that are trying to utilize that file:
import-test.py
import parse_csv
print(
parse_csv.toList('../data.csv')
)
I'm getting the following error when I run import-test.py:
Error
Traceback (most recent call last):
File "{system path placeholder}\directory-test\import-test.py", line 5, in <module>
parse_csv.toList('../data.csv')
File "{system path placeholder}\parse_csv.py", line 6, in toList
with open(file_location_name) as csv_file:
FileNotFoundError: [Errno 2] No such file or directory: '../data.csv'
My current project directory structure looks like this
Project
|
|--parse_csv.py
|--data.csv
|--directory-test
|
|--import-test.py
My first thought is that when I call open, '../data.csv' is being relatively referenced according to the parse_csv.py file instead of the intended import-test.py file.
I just want to make it so parse_csv.py can be imported anywhere and it will respect relative file paths in the calling file.
Please let me know if I need to be more clear. I know my wording may be confusing here.
Edit for clarity: The goal is to only call parse_csv.toList() and have it accept a string of a relative path to the file that called it.
You can have your parse_csv.toList function accept a file object instead of a file path. This way you open a file, give that to the module and it will work. Something like:
import parse_csv
with open('../data.csv') as csvFile:
print(parse_csv.toList(csvFile))
Or you can convert the relative path to absolute path before call toList. Refer How to get an absolute file path in Python. It'll just add one extra line.
In import-test.py,
import os.path
import parse_csv
# to retrieve import-test.py's own absolute path
abs_path = os.path.abspath(__file__)
# its dir_path
dir_path = os.path.dirname(abs_path)
# data.csv's path
csv_path = os.path.join(dir_path, '..', 'data.csv')
# use the path
print(
parse_csv.toList(csv_path)
)

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')

Why do I get this IOerror13 ? Using python

import sys
import os
import re
import ftplib
os.system('dir /S "D:\LifeFrame\*.jpg" > "D:\Python\placestogo.txt"') #this is where to search.
dat = open('placestogo.txt','r').read()
drives = re.findall(r'.\:\\.+.+',dat)
for i in range(len(drives)):
path = drives[i]
os.system('dir '+ path +'\*.jpg > D:\python\picplace.txt')
picplace = open('picplace.txt','r').read()
pics = re.findall(r'\w+_\w+.\w+..jpg|IMG.+|\w+.jpg',picplace)
for i in range(len(pics)):
filename = pics[i]
ftp = ftplib.FTP("localhost")
print ftp.login("xxxxxxxx","xxxxxxxx")
ftp.cwd("/folder")
myfile = open(path,"rb")
print ftp.storlines('STOR ' + filename, myfile)
print ftp.quit()
sys.exit()
i am trying to copy all of those files to my ftp server but it gives me that error:
d:\Python>stealerupload.py
230 Logged on
Traceback (most recent call last):
File "D:\Python\stealerupload.py", line 22, in <module>
myfile = open(path,"rb")
IOError: [Errno 22] invalid mode ('rb') or filename: '"D:\\LifeFrame"'
any one knows where is the problem ? I am running as administrator and folder should have permissions
The error seems pretty obvious. You are trying to open a directory path, which is neither possible nor what you actually want to do. This bit:
for i in range(len(drives)):
path = drives[i]
...
for i in range(len(pics)):
...
myfile = open(path,"rb")
Inside the loop you are setting path to be one of your drives elements. each of these items appears to be a directory path. Then you try to open path later, which is a directory path and not a file.
In the error message, it shows '"D:\\LifeFrame"', which to me looks like you have extra quotes in path. Try adding print path to see what its value is.
Maybe you want to upload data from filename to your server, not from path, in which case Python showed in the error message is where the bug is: you should be opening filename instead.

Bug in Python Renaming Program.....No such file or Directory (Fnmatch)

I'm trying to build a little renaming program to help save me time in the future.
Basically it will go through directories I point it too and rename files if they meet certain criteria.
I have written what I need but I have a bug in the very beginning that I can't figure out.
Here is the code:
import os
import fnmatch
for file in os.listdir("""/Users/Desktop/TESTME"""):
if fnmatch.fnmatch(file,'MISC*'):
os.rename(file, file[4:12] + '-13-Misc.jpg')
When I try to run it I am getting this:
Traceback (most recent call last):
File "/Users/Documents/Try.py", line 6, in <module>
os.rename(file, file[4:12] + '-13-Misc.jpg')
OSError: [Errno 2] No such file or directory
I also tried this:
if fnmatch.fnmatch(file,'MISC*'):
fun = file[4:12] + '-13-Misc.jpg'
os.rename(file, fun)
But I get the same thing.
It's not recognizing the file as a file.
Am I going about this the wrong way?
You'll need to include the full path to the filenames you are trying to rename:
import os
import fnmatch
directory = "/Users/Desktop/TESTME"
for file in os.listdir(directory):
if fnmatch.fnmatch(file, 'MISC*'):
path = os.path.join(directory, file)
target = os.path.join(directory, file[4:12] + '-13-Misc.jpg'
os.rename(path, target)
The os.path.join function intelligently joins path elements into a whole, using the correct directory separator for your platform.
The function os.listdir() only returns the file names of the files in the given directory, not their full paths. You can use os.path.join(directory, file_name) to reconstruct the full path of the file.
You could also do this in bash:
cd /Users/Desktop/TESTME/
for f in MISC*; do mv "$f" "${f:4:8}-13-Misc.jpg"; done

Categories