I am trying to replicate IDLE's alt + m command (open a module in the sys path) in Notepad++. I like Notepad++ for editing (rather than IDLE), but this is one feature I cannot find.
When alt+m is pressed, I want it to run a program that asks for a module (that's fairly straightforward, so I can do that). My problem is finding the module and then opening it in Notepad++, not simply running the program. In addition, I want it to open in the same instance (same window) in Notepad++, not a new instance.
I've tried this:
import os
f = r"D:\my_stuff\Google Drive\Modules\nums.py"
os.startfile(f, 'notepad++.exe')
However, I get this error:
Traceback (most recent call last):
File '_filePath_', line 3, in <module>
os.startfile(f, 'notepad++.exe')
OSError: [WinError 1155] No application is associated with the specified file for this operation: 'D:\\my_stuff\\Google Drive\\Modules\\nums.py'
How can I fix this?
Also, given a string, such as 'nums.py', how can I find the full path of it? It's going to be in one of two folders: 'D:\\my_stuff\\Google Drive\\Modules' or 'C:\\Python27\Lib' (it could also be in various subfolders in the 'Lib' folder). Alternatively, I could simply do:
try:
fullPath = r'D:\\my_stuff\\Google Drive\\Modules\\' + f
# method of opening file in Notepad++
except (IOError, FileNotFoundError):
fullPath = r'C:\\Python27\\Lib\\' + f
# open in Notepad++
This doesn't account for subfolders and seems rather clunky. Thanks!
If your .py files will be associated w/ notepad++ the os.startfile(f, 'notepad++.exe') will work for you (see ftype).
Unless, you would like to create this association , the following code will open notepad ++ for you:
import subprocess
subprocess.call([r"c:\Program ...Notepad++.exe", r"D:\my_stuff\Google Drive\Modules\nums.py"])
Reference: subprocess.call()
Related
I am quite new to working with Python files, and having a small issue. I am simply trying to print the name of a text file and its 'mode'.
Here is my code:
f = open('test.txt','r')
print(f.name)
print(f.mode)
f.close()
I have a saved a text file called 'test.txt' in the same directory as where I wrote the above code.
However, when I run the code, I get the following file not found error:
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
Any ideas what is causing this?
I have also tried to replace the first argument above with the path of the test.txt file, but I get the same error?
open (on pretty much any operating system) doesn't care where your program lies, but from which directory you are running it. (This is not specific to python, but how file operations work, and what a current working directory is.)
So, this is expected. You need to run python from the directory that test.txt is in.
I have also tried to replace the first argument above with the path of the test.txt file, but I get the same error?
In that case, you must have mistyped the path. Make sure there's no special characters (like backslashes) that python interprets specially in there, or use the raw string format r'...' instead of just '...'.
It depend from where the python command is launched for instance :
let suppose we have this 2 files :
dir1/dir2/code.py <- your code
dir1/dir2/test.txt
if you run your python commande from the dir1 directory it will not work because it will search for dir1/test.txt
you need to run the python commande from the same directory(dir2 in the example).
This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I'm trying to write a simple program to read a file and search for a word then print how many times that word is found in the file. Every time I type in "test.rtf" (which is the name of my document) I get this error:
Traceback (most recent call last):
File "/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/How many? (Python).py", line 9, in <module>
fileScan= open(fileName, 'r') #Opens file
FileNotFoundError: [Errno 2] No such file or directory: 'test.rtf'
In class last semester, I remember my professor saying you have to save the file in a specific place? I'm not sure if he really said that though, but I'm running apple OSx if that helps.
Here's the important part of my code:
fileName= input("Please enter the name of the file you'd like to use.")
fileScan= open(fileName, 'r') #Opens file
If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.
You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command
$ python script.py
In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.
In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.
Is test.rtf located in the same directory you're in when you run this?
If not, you'll need to provide the full path to that file.
Suppose it's located in
/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data
In that case you'd enter
data/test.rtf
as your file name
Or it could be in
/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder
In that case you'd enter
../some_other_folder/test.rtf
As noted above the problem is in specifying the path to your file.
The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).
Or you can specify the path from the drive to your file in the filename:
path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName
You can also catch the File Not Found Error and give another response using try:
try:
with open(filename) as f:
sequences = pick_lines(f)
except FileNotFoundError:
print("File not found. Check the path variable and filename")
exit()
A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:
import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")
This is with a little help from the built in module os, That is a part of the Standard Python Library.
You might need to change your path by:
import os
path=os.chdir(str('Here_should_be_the_path_to_your_file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
Difficult to give code examples in the comments.
To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words.
Split breaks up a String on the delimiter provided, or on whitespace by default. For example,
"the quick brown fox".split()
produces
['the', 'quick', 'brown', 'fox']
Similarly,
fileScan.read().split()
will give you an array of Strings.
Hope that helps!
First check what's your file format(e.g: .txt, .json, .csv etc ),
If your file present in PWD , then just give the name of the file along with the file format inside either single('')or double("") quote and the appropriate operation mode as your requirement
e.g:
with open('test.txt','r') as f: data=f.readlines() for i in data: print(i)
If your file present in other directory, then just give the full path name where is your file is present and file name along with file format of the file inside either single('')or double("") quote and the appropriate operation mode as your requirement.
If it showing unicode error just put either r before quote of file path or else put '/' instead of ''
with open(r'C:\Users\soman\Desktop\test.txt','r') as f: data=f.readlines() for i in data: print(i)
The mistake I did was
my code :
x = open('python.txt')
print(x)
But the problem was in file directory ,I saved it as python.txt instead of just python .
So my file path was
->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt
That is why it was giving a error.
Name your file without .txt it will run.
I'm trying to use a program to read from a file with pi-digits. The program and the text file with the pi-digits are in the same directory, but i still get the error message :
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
Traceback (most recent call last):
File "C:\Python\Python_Work\python_crash_course\files_and_exceptions\file_reader.py", line 1, in <module>
with open('pi_digits.txt') as file_object:
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
I have looked for a solution but haven't found any.
I found a piece of code which supposedly shows me what the working directory is. I get an output that shows a directory that is 2 steps above the directory i have my programs and text file inside.
import os
cwd = os.getcwd() # Get the current working directory (cwd)
files = os.listdir(cwd) # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))
So when i put the pi text document in the directory that the output is showing (>python_work), the program is working. When it does not work is when the text file is in ">files_and_exceptions" which is the same file the program itself is inside. My directory looks like this when it is not working:
>python_work
>python_crash_course
>files_and_exceptions
file_reader.py
pi_digits.txt
show_working_directory.py
And like this when it is working:
>python_work
pi_digits.txt
>python_crash_course
>files_and_exceptions
file_reader.py
show_working_directory.py
I'm new to python and really appreciate any help.
Thanks!
Relative path (one not starting with a leading /) is relative to some directory. In this case (and generally*), it's relative to the current working directory of the process.
In your case, given the information you've provided, for it would be "python_crash_course/files_and_exceptions/pi_digits.txt" in the first case as you appear to be running the script from python_work directory.
If you know the file to be in the same directory as the script itself, you could also say:
import os.path
...
os.path.join(os.path.dirname(__file__), "pi_digits.txt")
instead of "pi_digits.txt". Or the same using pathlib:
from pathlib import Path
...
Path(__file__).with_name("pi_digits.txt")
Actually unless you have a point to anchor to like the script itself, using relative filename / path (using absolute paths brings its own problems too) in the code directly is rather fragile and in that case getting it as a parameter of a function (and ultimately argument of CLI or script call in general) or alternatively reading it from standard input would be more robust.
* I would not make that an absolute statement, because there are situations and functions that can explicitly provide different anchor point (e.g. os.path.relpath or openat(2); or as another example a symlink target)
I'm trying to rename the file names and extensions of all the files in a directory and move them to a new directory. I've read multiple post on how to do it but for some reason I haven't been successful and I've been stuck on this for 3 days now and feel like I'm doing something careless. Somebody get me on track please.
This is the latest way I've been trying.
import os
previousName = 'Macintosh HD/Users/kunductor/Desktop/folder3/windeffect.asd'
newName = 'Macintosh HD/Users/kunductor/Desktop/folder4/wind.wav'
os.rename(previousName,newName)
When I run the code above I get the message:
Traceback (most recent call last):
File "rename.py", line 7, in <module>
os.rename(previousName,newName)
FileNotFoundError: [Errno 2] No such file or directory
If it matters, I'm using macOS Mojave, version 10.14.2.
I tried replicating the same using Python 3 on Mojave 10.14.2. Use the paths starting from '/Users', and don't include Macintosh HD. The code runs perfectly when both folder3 and folder4 exist. I got a similar error when folder4 was removed, and the error message also specified the paths I passed as parameters.
If that's what you're experiencing, ensure that the directory you're trying to move the file to exists before calling os.rename. This can be done in Python itself by using the os.mkdir method. Since it throws an error if the directory already exists, you can check that by using the os.path.exists method.
this is the code that worked. I think the problem was that i was trying to change a non-audio file to a .wav and the system was rejecting it.
import os
# Function to rename multiple files
def main():
i = 0
for filename in os.listdir('/Users/vfloyd/Desktop/uu/'):
dst ="Kick" + str(i) + ".wav"
src = '/Users/vfloyd/Desktop/uu/'+ filename
dst ='/Users/vfloyd/Desktop/newD/'+ dst
# rename() function will
# rename all the files
os.rename(src, dst)
i += 1
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
I have a very elementary question, but I've tried searching past posts and can't seem to find anything that can help. I'm learning about file i/o in Python. All the tutorials I've seen thus far seem to skip a step and just assume that a file has already been created, and just being by saying something like handleName = open('text.txt', 'r'), but this leaves 2 questions unanswered for me:
Do I have to create the file manually and name it? I'm using a Mac, so would I have to go to Applications, open up TextEdit, create and save the file or would I be able to do that through some command in IDLE?
I tried manually creating a file (as described above), but then when I tried entering openfile = open('test_readline', 'r'), I got the error: IOError: [Errno 2] No such file or directory: 'abc'
Regarding the error, I'm assuming I have to declare the path, but how do I do so in Python?
openfile = open('test_readline', 'w')
^^
Opening in write mode will create the file if it doesn't already exist. Now you can write into it and close the file pointer and it will be saved.
To be able to read from any file, the file must exist.Right? Now look here, file I/O has the syntax as shown below:
fp = open('file_name', mode) # fp is a file object
The second argument, i.e mode describes the way in which file will be used. w mode will open any existing file(if it exists) with the name as given in first argument. Otherwise it creates a new file with the same name. Beside, if you are on Windows and want to open a file in binary mode then append b to the mode. Eg. to open file to write in binary mode, use wb. Make a note that if you try to open any existing file in w (writing) mode then the existing file with the same name will be erased. If you want to write to the existing file without getting the old data erased, then use the a mode.It adds the new data at the end of the previous one.
fw = open('file_name','w')
fa = open('file_name','a') # append mode
To know in detail you can refer the doc at
Python File I/O.
I hope this helps!
Python will automatically use the default path.
import os
default_path = os.getcwd() ## Returns the default path
new_path = "C:\\project\\" ## Path directory
os.chdir(path) ## Changes the current directory
Once you change the path, the files you write and read will be in C:\project. If you try and read a project else where, the program will fail.
os.chdir is how you declare or set a path in python.
Do I have to create the file manually and name it?
Do you mean as a user, must you use existing tools to create a file, then return to Python to work on it? No. Python has all the tools necessary to create a file. As already explained by vks in their answer, you must open the file using a mode that will create the file if it doesn't exist. You've chosen read ('r') mode, which will (correctly) throw an error if there is no file to read at the location you've specified, which brings us to...
I'm assuming I have to declare the path, but how do I do so in Python?
If you do not (if you say, e.g., "filename.txt"), Python will look in its current working directory. By default, this is the current working directory of the shell when you invoke the Python interpreter. This is almost always true unless some program has changed it, which is unusual. To specify the path, you can either hardcode it like you're doing to the filename:
open('/full/path/to/filename.txt')
or you can build it using the os.path module.
Example:
I created an empty directory and opened the Python interpreter in it.
>>> with open('test.txt'): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'test.txt'
>>> with open('test.txt', 'w'): pass
...
>>>
As noted, read mode (the default) gives an error because there is no file. Write mode creates a file for us with nothing in it. Now we can see the file in the directory, and opening with read mode works:
>>> os.listdir(os.getcwd())
['test.txt']
>>> with open('test.txt'): pass
...
>>> # ^ No IOError because it exists now
Now I create a subdirectory called 'subdir' and move the text file in there. I did this on the command line but could have just as easily done it in Python:
>>> with open('test.txt'): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'test.txt'
>>> with open('subdir/test.txt'): pass
...
Now we have to specify the relative path (at least) to open the file, just like on the command line. Here I "hardcoded" it but it can just as easily be "built up" using the os module:
>>> with open(os.path.join(os.getcwd(), 'subdir', 'test.txt')): pass
(That is just one way it could be done, as an example.)