I am writing a python script in which I read a text file and I want to create a new text file in another directory.
I wrote the following code:
def treatFiles(oldFile, newFile):
with open(oldFile) as old, open(newFile, 'w') as new:
count = 0
for line in old:
count += 1
if count%2 == 0:
pass
else:
new.write(line)
if __name__ == '__main__':
from sys import argv
import os
os.makedirs('NewFiles')
new = '/NewFiles/' + argv[1]
treatFiles(argv[1], new)
I tried running this code with a text file in the same directory than my python script, but got an error like
FileNotFoundError: [Errno 2] No such file or directory: '/NewFiles/testFile'
Apparently, it is not clear that NewFiles is a directory in which it should create the new file... How can I correct this?
The problem is actually that in unix, /NewFiles/ means a folder in the root directory called NewFiles, not in the current directory. Remove the leading / and it should be fine.
Related
This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I have tried to get my program to open but it keeps saying FileNotFound
def main():
with open("number.txt") as f:
nums=[int(x) for x in f.read().split()]
print(nums)
for nums in nums:
total += int(nums)
print(total)
print(len(nums))
return total / len(nums)
main()
Is number.txt in your working directory? If not you'd have to specify the path to that file so python knows where to look
Python will look for "number.txt" in your current directory which by default is the same folder that your code started running in. You can get the current directory by using os.getcwd() and if that for some reason is not what you expect, you can also get the directory to the folder that your code is running in by doing current_directory = os.path.dirname(os.path.realpath(__file__)).
The following code should always work, if you want your "number.txt" to be in the same folder as your code.
import os.path
def main():
current_directory = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(current_directory, "number.txt")
# Optionally use this to create the file if it does not exist
if not os.path.exists(filepath):
open(filepath, 'w').close()
with open( filepath ) as f:
...
This question already has answers here:
How do you properly determine the current script directory?
(16 answers)
Closed 6 months ago.
def main():
fh = open('lines.txt')
for line in fh.readlines():
print(line)
if __name__ == "__main__": main()
Directory files
I am on for-working.py file, and am trying to access the lines.txt file within the same working directory. But I get error
No such file or directory: 'lines.txt'
Does python need to have an absolute path when opening files?
why doesn't this relative path work here?
Running python 3.6
EDIT ^1 I'm running visualstudio code with the python package extension by Don Jayamanne, and "Code Runner" package to compile/execute python code
EDIT ^2 Full error:
Traceback (most recent call last):
File "c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files\07 Loops\for-working.py", line 11, in <module>
if __name__ == "__main__": main()
File "c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files\07 Loops\for-working.py", line 7, in main
fh = open('lines.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'lines.txt'
EDIT ^3 checking sys.path
import sys
print(sys.path)
produces this information:
['c:\\www\\Ex_Files_Python_3_EssT(1)\\Ex_Files_Python_3_EssT\\Exercise Files\\07 Loops',
'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Kagerjay\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
EDIT ^4 checking os.getcwd()
Running
import os
print(os.getcwd())
Produces
c:\www\Ex_Files_Python_3_EssT(1)\Ex_Files_Python_3_EssT\Exercise Files
Well its definitely not in the right subdirectory (needs to cd 07 loops folder, that narrows the issue down
EDIT ^5 what is in lines.txt file
My lines.txt file i am opening looks like this. No extra whitespace or anything at start
01 This is a line of text
02 This is a line of text
03 This is a line of text
04 This is a line of text
05 This is a line of text
IN SUMMARY
Visual studio code's Code runner extension needs to be tweaked slightly to open files within a subdirectory so any of the below answers would provide a more robust solution to be independent of any extension / dependencies with the IDE
import os
print(os.getcwd())
Is most useful for diagnosing problem to the current directory python interpreter sees
Get the directory of the file, and join it with the file you want to open:
def main():
dir_path = os.path.dirname(os.path.realpath(__file__))
lines = os.path.join(dir_path, "lines.txt")
fh = open(lines)
for line in fh.readlines():
print(line)
if __name__ == "__main__": main()
This should do the trick.
def main():
fh = open('lines.txt')
for line in fh.readlines():
print(line)
if __name__ == "__main__":
import os
curr_dir = os.path.dirname(os.path.realpath(__file__)) # get's the path of the script
os.chdir(curr_dir) # changes the current path to the path of the script
main()
I faced the same trouble today. The solution was outside the code, in the environment.
Shows the picture of VSCode settings editor
Command prompt in VSCode opens with the directory where VSCode executable is placed. When you execute the code, Python is searching for the file in the location where the VSCode executable is located.
This setting can be changed to the directory that you are working in(shown in figure). So when you are running the code in yourprog.py file, the interpretor is started in your working directory.
Then the VScode runner will do the way you are thinking.
okay summary of working solutions to my problem from others not mentioned in post
Direct absolute path manually
def main():
fh = open('lines.txt')
for line in fh.readlines():
print(line)
if __name__ == "__main__":
import os
curr_dir = 'c:\\www\\Ex_Files_Python_3_EssT(1)\\Ex_Files_Python_3_EssT\\Exercise Files\\07 Loops'
os.chdir(curr_dir)
main()
I commented out unnecessary parts ... and open(lines at beginning
Below solution is very good for lazy implementation tests (e.g. copy-paste template), since all the absolute path correction code is up top seperated from everything else (my preferred solution)
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
lines = os.path.join(dir_path, "lines.txt")
# open(lines)
# ...
def main():
fh = open(lines)
for line in fh.readlines():
print(line)
if __name__ == "__main__": main()
Most robust solution would be this one below, since its self-contained only in the function definition when main() gets called. Original answer didn't include the import os so I included it here
def main():
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
lines = os.path.join(dir_path, "lines.txt")
fh = open(lines)
for line in fh.readlines():
print(line)
if __name__ == "__main__": main()
def Function222(inF):
inF = open("C:\\Users\\Dell\\Desktop\\FF1\\txttt.txt")
outputF=open("output.txt", "w")
lines=inF.readlines()
for line in lines:
outputF.write('\n')
outputF.write(line*4)
inF.close()
outputF.close()
I need to create a new file called outputF and it should show up in the same folder that the inF is in, the problem is that it doesn't appear in the folder and I searched for the file on my computer but didn't find it
Get the Path:
import os
path= os.path.abspath("C:/example/cwd/mydir/myfile.txt")
open new file in path and write to it
Because the current working directory isn't the directory of the input file. Use os.getcwd() to get the current working directory, if it doesnt't match the directory of the input file, then you need to change your working directory first:
import os
def Function222(inF):
inF = open("C:\\Users\\Dell\\Desktop\\FF1\\txttt.txt")
#change the working directory
os.chdir("C:\\Users\\Dell\\Desktop\\FF1")
outputF=open("output.txt", "w")
lines=inF.readlines()
for line in lines:
outputF.write('\n')
outputF.write(line*4)
inF.close()
outputF.close()
My Python script works perfectly if I execute it directly from the directory it's located in. However if I back out of that directory and try to execute it from somewhere else (without changing any code or file locations), all the relative paths break and I get a FileNotFoundError.
The script is located at ./scripts/bin/my_script.py. There is a directory called ./scripts/bin/data/. Like I said, it works absolutely perfectly as long as I execute it from the same directory... so I'm very confused.
Successful Execution (in ./scripts/bin/): python my_script.py
Failed Execution (in ./scripts/): Both python bin/my_script.py and python ./bin/my_script.py
Failure Message:
Traceback (most recent call last):
File "./bin/my_script.py", line 87, in <module>
run()
File "./bin/my_script.py", line 61, in run
load_data()
File "C:\Users\XXXX\Desktop\scripts\bin\tables.py", line 12, in load_data
DATA = read_file("data/my_data.txt")
File "C:\Users\XXXX\Desktop\scripts\bin\fileutil.py", line 5, in read_file
with open(filename, "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'data/my_data.txt'
Relevant Python Code:
def read_file(filename):
with open(filename, "r") as file:
lines = [line.strip() for line in file]
return [line for line in lines if len(line) == 0 or line[0] != "#"]
def load_data():
global DATA
DATA = read_file("data/my_data.txt")
Yes, that is logical. The files are relative to your working directory. You change that by running the script from a different directory.
What you could do is take the directory of the script you are running at run time and build from that.
import os
def read_file(filename):
#get the directory of the current running script. "__file__" is its full path
path, fl = os.path.split(os.path.realpath(__file__))
#use path to create the fully classified path to your data
full_path = os.path.join(path, filename)
with open(full_path, "r") as file:
#etc
Your resource files are relative to your script. This is OK, but you need to use
os.path.realpath(__file__)
or
os.path.dirname(sys.argv[0])
to obtain the directory where the script is located. Then use os.path.join() or other function to generate the paths to the resource files.
I'm trying to compute the maximum from each file in my data directory, with the following code:
from os import listdir
def max_files(dir):
l = listdir(dir)
for n in l:
list_num(n)
def list_num(file):
f = open(file)
lines = f.readlines()
v=[]
for n in lines:
for s in n.split():
v.append(float(s))
mx = v[0]
maxi=[]
for i in v:
if i > mx:
mx = i
maxi.append(mx)
continue
continue
return maxi
print max_files(path)
I also checked my path, and it's completely correct. The error is:
f = open(file)
IOError: [Errno 2] No such file or directory: 'bvp.txt'
bvp.txt is the first file listed in the data directory.
Why does this problem occur, and how do I fix it?
You've run into a common confusion when using the return value of functions that return lists of files in a directory.
listdir is just returning the list of files in that directory. It's not returning the path to those files, just the file name. So unless the directory on which you're operating is the current directory, this won't work; you're trying to open each file in the current directory.
Whenever using the results of listdir, if you're not going to change working directories into that directory, you need to add the directory name back to the file before you open it. Therefore, pass the full path to the file to list_num instead of just the file name:
list_num(dir + '/' + n)