I'm working on a python script to thoroughly mutilate images, and to do so, I'm replacing every "g" in the file's text with an "h" (for now, it will likely change). Here's the beginning, and it's not working:
pathToFile = raw_input('File to corrupt (drag the file here): ')
x = open(pathToFile, 'r')
print x
After giving the path (dragging file into the terminal), this is the result:
File to corrupt (drag the file here): /Users/me/Desktop/file.jpeg
Traceback (most recent call last):
File "/Users/me/Desktop/corrupt.py", line 7, in <module>
x = open(pathToFile, 'r')
IOError: [Errno 2] No such file or directory: '/Users/me/Desktop/file.jpeg '
How can the file not exist if it's right there, and I'm using the exact filename?
Look closely: '/Users/me/Desktop/file.jpeg '. There's a space in your filename. open doesn't do any stripping.
>>> f = open('foo.txt', 'w')
>>> f.write('a')
>>> f.close()
>>> f = open('foo.txt ', 'r')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'foo.txt '
Related
I have looked at How to open a list of files in Python This problem similar but not covered.
path = "C:\\test\\test5\\"
files = os.listdir(path)
fileNames = []
for f in files:
fileNames.append(f)
for fileName in fileNames:
pathFileName = path + fileName
print(f"This is the path: {pathFileName}")
fin = open(pathFileName, 'rt')
texts = []
with open(fileName) as file_in:
# read file text lines into an array
for text in file_in:
texts.append(text)
for text in texts:
print(text)
The file aaaatest.txt is in C:\test\test5 The output is:
This is the path: C:\test\test5\aaaatest.txt
Traceback (most recent call last):
File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'aaaatest.txt'
So here's the point. If I take a copy of aaaatest.txt (leaving original where it is) and put it in the current working directory. Running the script again I get:
This is the path: C:\test\test5\aaaatest.txt
A triple AAA test
This is the path: C:\test\test5\AALTONEN-ALLAN_PENCARROW_PAGE_1.txt
Traceback (most recent call last):
File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'AALTONEN-ALLAN_PENCARROW_PAGE_1.txt'
The file aaaatest.txt is opened and the single line of text, contained in it, is outputted. Following this an attempt is made to open the next file of C:\test\test5 where the same error occurs again.
Seems to me that while the path is saying C:\test\test5 the file is only being read from the cwd?
I have written this Python script that checks if a file exists in a web server. And if it does exist, it copies is in the "found" directory on the local machine. However, since the web server is running Linux, and the full file path has slashes in it, it shows some errors. I have tried to solve it with "os.path" module but have been unsuccessful in my attempts.
import requests
import sys
import re
regex = re.compile(r"header(.*) footer", re.DOTALL)
data = {
"name":"user01",
"password":"secret"
}
r = requests.post('http://10.10.10.10/posts', data=data)
file = re.search(regex, r.text)
filename = sys.argv[1]
if file.group(1) != 'None':
with open('found/' + filename, 'w') as f:
f.write(file.group(1))
print("Found: ", filename)
I get the following error:
ERROR
Traceback (most recent call last):
File "/home/shit.py", line 18, in <module>
with open('found/' + filename, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'found//boot/grub/grub.cfg'
Traceback (most recent call last):
File "/home/shit.py", line 18, in <module>
with open('found/' + filename, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'found//etc/adduser.conf'
Traceback (most recent call last):
File "/home/shit.py", line 18, in <module>
with open('found/' + filename, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'found//etc/apache2/apache2.conf'
I have come up with a workaround. All I have to do is use:
filename = sys.argv[1].replace("/", "_")
It saves the files with an "_" instead of "/". For example, it saves "/etc/passwd" as "_etc_passwd".
I have a code where I call a Node script. The javaScript named preprocess_latex.js is in the same directory as filter_tokenize.py. Every directory has __init__.py so I can call the modules.
My code looks like this:
def tokenize(latex:str,kind:str='normalize')->list:
'''
Tokenize the incoming LaTex. This uses subscripts based on Node and Perl which uses bash call to KaTex. It also creates 2 .lst files in the same directory where the function is being called
args:
latex: Latex string
out:
List of cleaned tokens per LaTex
'''
path = pathlib.Path(__file__).parent.absolute() # When you call this module, it'll give the path of THIS file instead of the Current Working Directory
output_file = os.path.join(path,'out.lst')
input_file = os.path.join(path,'input_file.lst')
js_file_path = os.path.join(path,"preprocess_latex.js").replace(' ','\\ ')
with open(input_file,'w') as f:
f.write(latex+'\n')
cmd = "perl -pe 's|hskip(.*?)(cm\\|in\\|pt\\|mm\\|em)|hspace{\\1\\2}|g' %s > %s"%(input_file, output_file) # Call Perl subscript
ret = subprocess.call(cmd, shell=True)
cmd = f"cat {temp_file} | node {js_file_path} {kind} > {output_file} "
ret = subprocess.call(cmd, shell=True)
Problem is that I have spaces in my directories and when I do:
from latex_utils.filter_tokenize import *
tokenize('some_string')
it gives me error as:
Can't open Improve/Latex/latex_simialarity/latex_utils/input_file.lst: No such file or directory.
Can't open Improve/Latex/latex_simialarity/latex_utils/out.lst: No such file or directory.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/admin1/Desktop/Work/Search Improve/Latex/latex_simialarity/latex_utils/filter_tokenize.py", line 31, in tokenize
with open(output_file) as fin:
FileNotFoundError: [Errno 2] No such file or directory: '/home/admin1/Desktop/Work/Search Improve/Latex/latex_simialarity/latex_utils/out.lst'
I tried with output_file.replace(' ','\\ ') and there was a different error as:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/admin1/Desktop/Work/Search Improve/Latex/latex_simialarity/latex_utils/filter_tokenize.py", line 23, in tokenize
with open(input_file,'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: '/home/admin1/Desktop/Work/Search\\ Improve/Latex/latex_simialarity/latex_utils/input_file.lst'
I am trying to create a text file, using open(filename,'x'). I have tried x = 'a+', 'w+', 'w'. I am using windows 10, vs code "run python file in terminal", and python 3.8.2
import os
print("cwd",os.getcwd())
scriptpath = os.path.dirname(__file__)
filename = "test.txt" #1
#filename = scriptpath + "/test.txt" #2
#filename = r"C:\Users\harki\Documents\ALGO\ALGO-NPL\test.txt" #3
f = open(filename,'w+')
f.write("test")
f.close()
running with first filename:
PS C:\Users\harki\Documents\ALGO\ALGO-NPL> & C:/Users/harki/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py
cwd C:\Users\harki\Documents\ALGO\ALGO-NPL
Traceback (most recent call last):
File "c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py", line 11, in <module>
f = open(filename,'w+')
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
running with second filename:
PS C:\Users\harki\Documents\ALGO\ALGO-NPL> & C:/Users/harki/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py
cwd C:\Users\harki\Documents\ALGO\ALGO-NPL
Traceback (most recent call last):
File "c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py", line 11, in <module>
f = open(filename,'w+')
FileNotFoundError: [Errno 2] No such file or directory: 'c:/Users/harki/Documents/ALGO/ALGO-NPL/test.txt'
running with third filename:
PS C:\Users\harki\Documents\ALGO\ALGO-NPL> & C:/Users/harki/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py
cwd C:\Users\harki\Documents\ALGO\ALGO-NPL
Traceback (most recent call last):
File "c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py", line 11, in <module>
f = open(filename,'w+')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\harki\\Documents\\ALGO\\ALGO-NPL\\test.txt'
Edit:
Moving project outside of "Documents" folder solved the problem
I used this code to define file path and it works for me:
filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'folder/name', 'test.txt')
And then I create the file by using joblib or pickle.
In your case, it is similar to the second filename, just need to add the join() function
I want to create and write a .txt file in a hidden folder using python. I am using this code:
file_name="hi.txt"
temp_path = '~/.myfolder/docs/' + file_name
file = open(temp_path, 'w')
file.write('editing the file')
file.close()
print 'Execution completed.'
where ~/.myfolder/docs/ is a hidden folder. I ma getting the error:
Traceback (most recent call last):
File "test.py", line 3, in <module>
file = open(temp_path, 'w')
IOError: [Errno 2] No such file or directory: '~/.myfolder/docs/hi.txt'
The same code works when I save the file in some non-hidden folder.
Any ideas why open() is not working for hidden folders.
The problem isn't that it's hidden, it's that Python cannot resolve your use of ~ representing your home directory. Use os.path.expanduser,
>>> with open('~/.FDSA', 'w') as f:
... f.write('hi')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '~/.FDSA'
>>>
>>> import os
>>> with open(os.path.expanduser('~/.FDSA'), 'w') as f:
... f.write('hi')
...
>>>