How to read home directory in Python - python

I'm trying to write a python script that will copy some files into certain directories and then add a source to my .bash_profile. I am having some issues even getting this script off the ground. I am currently trying to just check if there is a .bash_profile and if so read the contents
import os.path
def main():
file_path = '~/.bash_profile'
file_exists = os.path.isfile(file_path)
if file_exists:
print('file exists')
f = open(file_path, "r")
if f.mode == "r":
contents = f.read()
print(contents)
else:
print('file does not exist')
if __name__== "__main__":
main()
if I take my code out of the if statement I receive this error
Traceback (most recent call last):
File "bash_install.py", line 9, in <module>
main()
File "bash_install.py", line 3, in main
f = open('~/.bash_profile', "r")
IOError: [Errno 2] No such file or directory: '~/.bash_profile'
I can't seem to find any information on how to read into the home ~ directory or is this an issue with .bash_profile being a hidden file? Any direction would be much appreciated

You need to call os.path.expanduser(file_path) to expand the path that starts with ~.

~ to get home path from this use os.path.expanduser function.
import os
f = open(os.path.expanduser('~/.bash_profile') , "r")

~ is expanded by the shell, it has no special meaning for python.

Related

Python open("file", "w+") not creating a nonexistent file

Similar questions exist on Stack Overflow. I have read such questions and they have not resolved my problem. The simple code below results in a File Not Found Error. I am running Python 3.9.1 on Mac OS X 11.4
Can anyone suggest next steps for troubleshooting the cause of this?
with open("/Users/root/test/test.txt", "w+") as f:
f.write("test")
Traceback (most recent call last):
File "/Users/root1/PycharmProjects/web_crawler/test.py", line 1, in <module>
with open("/Users/root/test/test.txt", "w+") as f:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/root/test/test.txt'
You comments on initial post clarify what you need to happen.
Below assumes that
The directory Users/root1/ exists
You are trying to create a new sub directory + file inside it
import os
# Wrap this in a loop if you need
new_dir = 'test' # The variable directory name
new_path = 'Users/root1/' + new_dir + "/"
os.makedirs(os.path.dirname(new_path), exist_ok=True) # Create new dir 'Users/root1/${new_dir}/
with open(new_path + "test.txt", "w+") as f:
# Create new file in afore created directory
f.write("test")
This creates a new directory based on a variable new_dir and creates the file test.txt in it.
**sometimes the compiler can't find any path like that you insert in open() function. at that time as possible you can save by default in the folder where your programs were saved by IDE. the followed syntax may be helpful for you **
with open('test.txt', 'w+') as f:
f.write("xyz")
**here the text.txt will save default in the folder where your IDE stores the program that you write. you can check that folder for conformation **

IOError: [Errno 13] Permission denied while opening file

studying foundation year ComSci and I'm trying to get a file to open. Here's my code:
def main():
filename = raw_input("Please enter file name ")
infile = open(filename,'r')
data = infile.read()
print data
main()
I believe the code is correct but when I try and open a file, for example
C:\Users\Manol\OneDrive\Documents\Uni\Programming\File Processing File
It comes back with
Traceback (most recent call last):
File "C:\Users\Manol\OneDrive\Documents\Uni\Programming\File Processing File\FirstFileProcessingRead.py", line 6, in <module>
main()
File "C:\Users\Manol\OneDrive\Documents\Uni\Programming\File Processing File\FirstFileProcessingRead.py", line 3, in main
infile = open(filename,'r')
IOError: [Errno 13] Permission denied: 'C:\\Users\\Manol\\OneDrive\\Documents\\Uni\\Programming\\File Processing File'
Aside from your permissions problem, does open() not need the file extension to function correctly?
aa = open("C:\\aaa\\bbb\\ccc\\ddd.json","r")
will work, whereas
aa = open("C:\\aaa\\bbb\\ccc\\ddd","r")
will return
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\aaa\\bbb\\ccc\\ddd'
As a way of testing folder permissions - copy the file to the same area as your .py and try opening it there. If you've still got same problems, then does your account have rights to the file? (right-click >> security)
See if file is encrypted and put two Backslash ( \\ ) or replace to Forward slash ( / ) and put extension of file
I change a few your code.
def main():
print("Please enter file name:")
filename = input()
infile = open(filename,'r')
data = infile.read()
print(data)
main()
Problem:
While installation when you select install python only for me then this issue is likely to happen because python is not granted with the permission to read every location, in your case One Drive.
Solution:
Place the file in your python file's root folder i.e inside the folder where you have placed the python file, then this will work.
You are also not providing extension (.txt). Don't forget to provide it while inputting the data.

Iterating and modifying files in a directory

I already have code that works to modify one .edi file (testedifact.edi) in the same directory as my program.
however I need to run my script against a folder containing many of these .edi files so I basically want to use my code to be applied to every single file
here's what I have that works on one file:
segmentsNew = []
global segments
with open( "testedifact.edi" , "r+") as edifactile:
segments = edifactile.readlines()
versionNumber = getVersionNumber(segments)
for segment in segments:
#do stuffs
edifactile.close()
with open ("testedifact.edi" , "w") as edifactfile:
edifactile.writelines(segmentsNew)
edifactfile.close()
but I want to be able to do this for files outside of this directory and also on our network drives..
I've tried iterating through the files in my directory (as a little test) and passing every file to "with open.." like this
directory = os.listdir(r'C:\Users\name\test_edi_dir')
for file in directory:
print("printing file names:", file)
with open(file, 'r') as edifactfile:
pass
print(edifactfile.closed)
and I keep getting FileNotFoundError: [Errno 2] No such file or directory: 'testedifact - Kopie (10).edi' though it prints the file name.. what am I doing wrong?
could someone help please?
file only contains the file-name, not the path it is stored in. You need to pass this, too.
path = r'C:\Users\name\test_edi_dir/'
directory = os.listdir(path)
for file in directory:
print("printing file names:", file)
with open(path+file, 'r') as edifactile:
pass
That happens because when you call open(file, 'r') it tries to open a file in the current working directory.
Change your code to this:
directory = os.listdir(r'C:\Users\name\test_edi_dir')
for file in directory:
print("printing file names:", file)
with open('C:\Users\name\test_edi_dir\' + file, 'r') as edifactile:
pass
print(edifactfile.closed)
The next issue is that some files will be actually a directories, and your code may fail with the following error:
traceback (most recent call last):
File "<stdin>", line 3, in <module>
IOError: [Errno 21] Is a directory: '...'
So you want to check if file is actually a file, before opening it:
isFile = os.path.isfile('C:\Users\name\test_edi_dir\' + file)
And finally a complete code is:
directory = os.listdir(r'C:\Users\name\test_edi_dir')
for file in directory:
print("printing file names:", file)
full_filename = 'C:\Users\name\test_edi_dir\' + file
if os.path.isdir(full_filename):
continue
with open(full_filename, 'r') as edifactile:
pass
print(edifactfile.closed)
Looks like you have to pass the entire image path:
with open('C:\Users\name\test_edi_dir\' + file, 'r') as edifactile:
pass

FileNotFoundError: [Errno 2] - Possible work network issue?

I am trying to read content of a file on my work network from my work network. I copy and pasted a code snippet from a google search and modified it to the below. Why might I still be getting [Errno 2] (I have changed some of the path names for this question board)
The file path in my file explorer shows that "> This PC > word common common" and I don't have "This PC" in my path. I tried adding that into the place I would think it goes in the string. That didn't solve it.
I tried making sure I have matching capitalization. That didn't solve it.
I tried renaming the file to have a *.txt on the end. That didn't solve it.
I tried the different variations of // and / and \ with and without the r predecessor and while that did eliminate the first error I was getting. It didn't help this error.
(Looking at the code errors in the right gutter is says my line length is greater than the PEP8 standard. While I doubt that is the root of my problem, if you can throw in the 'right' wrap method for a file path that long that would be helpful.)
myfile = open("z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246", "rt") # open lorem.txt for reading text
contents = myfile.read() # read the entire file into a string
myfile.close() # close the file
print(contents) # print contents
Full Error Copy:
C:\Users\e087680\PycharmProjects\FailureCompiling\venv\Scripts\python.exe C:/Users/e087680/PycharmProjects/FailureCompiling/FirstScriptAttempt.py
Traceback (most recent call last):
File "C:/Users/e087680/PycharmProjects/FailureCompiling/FirstScriptAttempt.py", line 1, in
myfile = open("z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246", "rt") # open lorem.txt for reading text
FileNotFoundError: [Errno 2] No such file or directory: 'z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246'
EDIT
DEBUG EFFORTS
working to figure out how to change directory. Just in case that is the problem. Tested this code bit
import os
path = "z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246"
os.chdir(path)
isExist = os.path.exists(path)
print(isExist)
Received this error
C:\Users\e087680\PycharmProjects\FailureCompiling\venv\Scripts\python.exe C:/Users/e087680/PycharmProjects/FailureCompiling/ScriptDebugJunkFile.py
Traceback (most recent call last):
File "C:/Users/e087680/PycharmProjects/FailureCompiling/ScriptDebugJunkFile.py", line 5, in <module>
os.chdir(path)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246'
My intention for adding the picture below is to show how File Explorer displays the file path for my file
FileExplorerPathScreenShot
EDIT
I think this confirms that my 'OS' doesn't have my file.
from os import path
path.exists("PCC_ESS_FC_Full_Report_65000122-1_R0016_962019_9246")
def main():
print ("File exists:" + str(path.exists('PCC_ESS_FC_Full_Report_65000122-1_R0016_962019_9246')))
if __name__== "__main__":
main()
Output
File exists: False
I thought OS was a standard variable for Operating system. Now I'm not sure.
EDIT
Using Cmd in DOS, I confirmed that my path for the z: is correct
EDIT - Success
I ran
import os
print( os.listdir("z:/"))
Confirmed I don't need the monster string of folders.
Confirmed, although explorer doesn't show it, it is a *.txt file
Once I implemented these two items the first code worked fine.
Thank you #Furas
To open and read a file specify the filename in your path:
myfile = open("U:/matrix_neo/word common common/hello world.txt", "rt") # open file
contents = myfile.read() # read the entire file into a string
myfile.close() # close the file
print(contents) # print contents
The U: is a mapped drive in my network.
I did not find any issue with your change dir example. I used a path on my U: path again and it returned True.
import os
path = "U:/matrix_neo/word common common"
os.chdir(path)
isExist = os.path.exists(path)
print(isExist)
The check the attributes on the directory that you are trying to read from. Also try to copy the file to a local drive for a test and see if you can read the file and also check if it exists.
This is an alternative to the above and uses your path to make sure that the long file path works:
import os
mypath = "z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246"
myfile = 'whatever is your filename.txt'
if not os.path.isdir(mypath):
os.makedirs (mypath)
file_path = os.path.join(mypath, myfile)
print(file_path)
if os.path.exists(file_path) is True:
with open(file_path) as filein:
contents = filein.read()
print(contents)
I tested this code using a long csv file.,Replace the variable myfile with whatever is your file name.

How to fix: FileNotFoundError: [Errno 2] No such file or directory

I'm having an issue trying to open a file that is definitely saved to my computer ('NYT-bestsellers.txt'), but whenever I try opening it with my code I get the error
FileNotFoundError: [Errno 2] No such file or directory: 'NYT-bestsellers.txt'
I thought about using the method where you use the full path to open the fileā€¦ but this is part of an assignment that I'll be submitting later this week. If I open the file using a specific path from my laptop, I'm worried that it won't open for the marker. Please advise!
with open('NYT-bestsellers.txt', 'r') as file:
file = file.splitlines()
As Ryan said, every time you open a file by a relative name, you need to make clear for the current work path.
import sys
import os
current_work_directory = os.getcwd() # Return a string representing the current working directory.
print('Current work directory: {}'.format(current_work_directory))
# Make sure it's an absolute path.
abs_work_directory = os.path.abspath(current_work_directory)
print('Current work directory (full path): {}'.format(abs_work_directory))
print()
filename = 'NYT-bestsellers.txt'
# Check whether file exists.
if not os.path.isfile(filename):
# Stop with leaving a note to the user.
print('It seems file "{}" not exists in directory: "{}"'.format(filename, current_work_directory))
sys.exit(1)
# File exists, go on!
with open(filename, 'r') as file:
file = file.splitlines()
If you confirm that the file will be along with your python script file, you can do some preparatory work before opening the file:
script_directory = os.path.split(os.path.abspath(__file__))[0]
print(script_directory)
abs_filename = os.path.join(script_directory, filename)
print(abs_filename)
with open(abs_filename, 'r') as file:
file = file.splitlines()

Categories

Resources