i have two python scripts
script1.py1:-
def somefunction()
.................
out_file = open("out.txt","w")
#creates a file out.txt and write something into it
out_file.close()
.................
.................
somefunction() #calling somefunction
out_file = open("out.txt","r")
output = open("Final_out.txt","w")
for line in out_file:
match_for_pattern = re.search(r"^\(.*affected\)$",line)
if match_for_pattern:
output.write("")
else:
output.write("%s" % line)
out_file.close()
output.close()
I wanted to change something in out.txt file, i.e removing some unwanted lines, So i thought to create a new file Final_out.txt with all the changes done in it.
but i'm getting permission denied error when i run the code
ERROR:-
output = open("Final_out.txt","w")
IOError: [Errno 13] Permission denied: 'Final_out.txt'
I have full permission chmod 777 in my present working directory,
If i take out the code where i am changing something in my file(out.txt) and place it into a new python script (script2.py) then it is working.
scritp2.py:-
out_file = open("out.txt","r")
output = open("Final_out.txt","w")
for line in out_file:
match_for_pattern = re.search(r"^\(.*affected\)$",line)
if match_for_pattern:
output.write("")
else:
output.write("%s" % line)
out_file.close()
output.close()
script2.py creates a file Final_out.txt in my present directory with all the changes that i want.
how's this possible that my script1.py is not able to do this but script2.py does it without any errors?
Related
This is a school program to learn how to use file and directory in Python. So to do my best I create a function to open, set it as a variable and close properly my file.
But I got the error of the title:
FileNotFoundError: [Errno 2] No such file or directory: 'codedata.pkl'
def load_db():
""" load data base properly
And get ready for later use
Return:
-------
cd : (list) list of tuples
"""
file = open('codedata.pkl', 'rb')
codedata = pickle.loads(file)
file.close()
return codedata
From the interpreter, this is the line
file = open('codedata.pkl', 'rb')
Which is the problem, but I don't see where is the source of the problem.
Can anyone help me?
Can you check what is the location of the file?
If your file is located at /Users/abc/Desktop/, then the code to open the file on python would be as shown below
file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
codedata = pickle.load(file)
file.close()
You can also check if the file exists at the desired path by doing something like this
import os
filepath = '/Users/abc/Desktop/codedata.pkl'
if os.path.exists(filepath):
file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
codedata = pickle.load(file)
file.close()
else:
print("File not present at desired location")
it happens when you run the script without determining it's the current working directory (example in vs code if you go to Explorer Tape )
You do not work from the same directory that your data.pkl in that's why No file exists
You can know the current directory from getcwd() usually it will be the C/User/.
print(os.getcwd())
filepath=""
if os.path.exists(r"D:\research\StleGAN\karras2019stylegan-ffhq-1024x1024.pkl"):
print("yes")
else:
print("no")
The solution is to open a directory that contains the script or to add the full path.
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.
I created a .exe file with Pyinstaller. The program should create a data file with the results at runtime. It works in the Python interpreter mode when I execute python test.py but it doesn't work in the .exe mode. It simply doesn't create a file and responds with an error.
Which flags should I add to the command python -m PyInstaller --hidden-import=timeit --hidden-import=bisect -F test.py to make it work?
The exception with this setup is:
Error: [Errno 2] No such file or directory: "C:\Users\Admin\AppData\Local\Temp\..."
Where the aforementioned directory is temporary and I don't have access to it.
The piece of code which is supposed to write a file is:
def write_file(data, path, encoding='utf-8'):
'''Creates report files.'''
try:
if config.python_version == 2 and type(data) in (list, str):
f = io.open(path, 'wb')
else:
f = io.open(path, 'w', encoding=encoding, newline='')
if type(data) is list:
writer = csv.writer(f)
writer.writerows(data)
else:
f.write(data)
f.close()
console(u'Report file: ' + path)
except IOError as e:
console(e, level=Level.error)
I assume there should be a setting to point to the place where the file should be saved.
I've checked here https://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-files-to-the-bundle but without success. I couldn't use the listed flags properly, nothing seemed to work.
How can I specify the place where the file would be saved?
The issue isn't with pyinstaller, it's with however you're creating your file.
You may be using some environment variable when running your python script from the command line that isn't set when you run your Exe
I have created a simple example of a program that creates a data file in the directory from which it is called:
#myscript.py
f = open("Test.txt", "w")
print("Hello World!", file=f)
Then I generate the Exe with Pyinstaller:
pyinstaller -F myscript.py
Copy the exe anywhere and you can create Test.txt, if you have permissions in that folder.
Double click myscript.exe
Test.txt appears in the same folder as myscript.exe
Hello World!
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
I'm working with python 2.7x. I'm quite new to python and will really appreciate your help. I have read many posts including those shown below to name a few about this error:
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'new.dat' --> my file close instruction is at the end already.
python 2 [Error 32] The process cannot access the file because it is being used by another process --> I can't use shutil as there's some error in the python program I'm using and I cant edit the pathway as my computer is adminstrative protected.
Rename Files in Python -->After following the suggestion, I got NameError: name 'rename' is not defined instead... :/
etc etc.
After trying to rectify my codes, I'm still getting the same error.
What I would like to do is: I read the files in a directory, if any of the files contains a specific string, I would rename the text file
(i.e. first.txt to firstfound.txt.)
EDITED VERSION:
I tried moving the abc.close() before I rename the file:
import os
fname = raw_input("Enter file name: ")
#fill in file directory here
abc = open(fname)
for line in abc:
if not line.find("scramble") :
continue
oldfile = fname
abc.close()
if oldfile == fname:
for title in fname:
endname = title.find('.txt')
oldtitle = title[:endname]
newfile = oldtitle +"found.txt"
os.rename(oldfile,newfile)
But I have this error instead for the last line.
os.rename(oldfile,newfile)
WindowsError: [Error 183] Cannot create a file when that file already exists. There's no file with the new name in my folder.
Thanks so much for your advice!
EDITED VERSION 2: I have also tried this other set of codes but it gave me WindowsError: [Error 5] Access is denied. May I know if there's such a thing that I cannot rename the txt file because I have no administrator privilege? Thank you!
import os
fname = raw_input("Enter file name: ")
#fill in file directory here
abc = open(fname)
for line in abc:
if not line.find("scramble") :
continue
oldfile = fname
abc.close()
if (oldfile == fname): #+'/' + "a.txt"
for title in fname:
endname = title.find('.txt')
oldtitle = title[:endname]
new_file = oldtitle +'/' + "a.txt"
os.rename(fname,new_file)
INITIAL version: The error I got is at the os.rename line. "WindowsError: [Error 32] The process cannot access the file because it is being used by another process"
My whole program code is as shown below:
import os
fname = raw_input("Enter file name: ")
#fill in file directory here
abc = open(fname)
for line in abc:
if not line.find("scramble") :
continue
old_file = fname
for title in fname:
endname = title.find('.txt')
oldtitle = title[:endname]
new_file = oldtitle +'/' + "found.txt"
os.rename(old_file,new_file) ##WindowsError: [Error 32] The process cannot access the file because it is being used by another process
abc.close()
I don't understand why this error persists. (I have closed all the files & folders). Thank you very much!
The problem is most likely due to your open() call in your code. The open() function in python opens file file for reading/writing, so if you open a file then you cannot call rename on it as it is open in another location.
Instead you should call
abc.close()
before renaming your file.
See this link for more information regarding file I/O.