I'm using Geany as my editor and when I first started using it, writing to files worked fine but somehow it randomly stopped working. The code executes without any errors but the file isn't created / is empty if already created and I've no idea why.
Simple code as below doesn't work:
filename = 'dogs'
with open(filename, 'w') as f:
f.write('tester')
with open(filename, 'r') as f:
contents = f.read()
print(contents)
The output I get from the 'read' method looks correct on the console output (it just prints 'tester'), but no file is created / edited in my directory.
Geany also has a weirdly complex debugger (if anyone has any helpful guides on how to use it please let me know) so I can't debug properly. I've tried all that I know including using an absolute file path, running in admin mode. The issue is also present when I try to use Pygal to render_to_file(), which is the project I'm working on so right now I can't go any further because anything that requires writing doesn't work. FYI it reads fine.... It's like Geany doesn't have admin rights or something?
EDIT: I've run this code on a python shell (without a .py file) and it worked fine, creating the file as desired. I then ran it using CMD with the .py file and it didn't work. Also ran using Pycharm, it doesn't work when I run it normal but it works when I run it in debug mode? It doesn't seem to be a Geany specific issue, but I am so confused!
Because the code works in the shell I strongly suspect the file is being created somewhere but you are looking in the wrong place.
I know you mentioned absolute paths but I just want to reiterate that you are not currently using an absolute path. An absolute path must start with a '/' (linux/mac) or something like: 'C:/' (windows).
Here are 2 things to try:
1)
Change the name 'dogs' to something really obscure and then do a global search on your whole hard disk for that name. You'll probably find it.
2) Get python to tell you where the file is like this:
import os
filename = 'dogs'
with open(filename, 'w') as f:
f.write('tester')
print(os.path.realpath(f.name))
Got the solution - the files were being created the whole time every time I ran my code, however my antivirus software Comodo contained them within a hidden folder in my drive which couldn't be found by a normal search.
I'm not sure if this a common problem with AV software or just Comodo, can't find anything on the net about it but there you go. I removed these files and the programs from its radar and it now works perfectly.
Although one mystery is how the python shell bypassed that problem. That threw me off thinking it was AV.
Related
I am currently learning python and my instructor is telling me to open a text file using the open() meathod. I get the following error each time:
FileNotFoundError: [Errno 2] No such file or directory: 'movies.txt'
I have tried using online guides but all I could find was for .csv files, whereas I'm trying to open a text file. My complete code is as follows:
with open('movies.txt') as file_object:
contents = file_object.read()
print(contents.strip())
I've tried writing the file 'movies.txt' in VS code, and in my notepad, and then saving it to the same directory as the code but no use. I have also attempted to use a more exact file source, but still the same error. Sadly, google didn't have too much information for text files so I have to come here. Is there something I have to change in VS settings? I also tried my code in IDLE but not response either.
Thanks,
Stan
First of all you have to make sure that the file you are looking is in the same folder as your script as you are giving just the name and not the path.
Then the code to read a file misses a parameter:
with open('movies.txt', 'r') as file_object:
contents = file_object.read()
print(contents.strip())
r: read
w: write
a: append
The code is ok, the problem is finding the object as the error states. As you write it, it looks like "movies.txt" is in the same directory as the script. Are you sure they are in the same directory? Otherwise you will have to set the whole route
This is not about the directory your code is in. This is about the current working directory. These two directories may or may not be the same in some specific circumstance, but treating them as the same thing will lead to confusion in the future.
I don't know about VS Code (haven't worked with it), but all IDEs I've worked with have an option to set the current working for code you're running from the IDE.
I ended up using the run & debug function in VS, and it works. I dont understand what it debugged. All the information it gave me was my .vscode files? I guess its fine for now? Is it possible that the issue was caused by something else I have downloaded on my laptop?
Thanks,
Stan
I want to run the main app which is connected with database, my.kv, users.txt file but when I run it it's showing me erroe message.. I made this project in window but when I try to run it in mac os it's showing me error.. please help me out guys
It seems your trying to access the 'users.txt' file as if it were in the current directory. Frequently, IDEs will put the working directory somewhere else that may be inconvenient for you. You can either try to play around with these settings until you get it treat the directory you expect to be the correct directory as the working directory, or you can try working with absolute paths.
For example, if your sure you app will always have this data file right next to your 'main.py' file, you could do something like the following:
import os
def get_users_file():
current_python_script = os.path.abspath(__file__)
current_script_directory = os.path.dirname(current_python_script)
users_file = os.path.join(current_script_directory, 'users.txt')
return users_file
with open(get_users_file(), 'r') as file_handler:
users_file_data = file_handler.readlines()
print(users_file_data)
there are other, cleaner ways to do this with things like pkg_resources, but I typically don't bother with using things like that until I have a proper build environment for my program.
In the future, I also recommend putting the bulk of your question into text form rather than a screen shot, as it makes it more difficult to decipher what you want.
I have a linux server.
It is reading files in a directory and doing things with the full text of the file.
I've got some code. it retrieves the file path.
And then I'm doing this:
for file in files:
with open(file,'r') as f:
raw_data = f.read()
Its reading the file just fine. And Ive used this exact code outside of the server and it worked as expected.
In this case, when run on the server, the above code is spitting out all the text to the terminal. But then raw_data == None.
Not the behavior I'm used to. I imagine its something very simple as I am new to linux in general.
But I'm wanting the text in the file to be stored in the 'raw_data' variable as a string.
is there a special way I am to do this on linux? Googling so far as not helped much and I feel this is likely a VERY simple problem.
User error.
I thought, due to my noob status in linux, that perhaps the enviroment was causing weird behavior. But buried deep in the functions that use the data from the files was a print statement i had used a while back for testing. That was causing the output to screen.
As for the None type being returned. It was being returned by another subfunction that had a try/except block in it and was failing. The variable being referenced had the same name (raw_data). So i thought it came from the file read. But it was actually from elsewhere.
thanks all who stopped by. User error for this one.
I am having problems with Project Multiclipboard from Chapter 8 of the book: Automate the Boring Stuff and using Python 3.
The first issue is that, suppose my program mcb.pyw is saved in:
C:\Users\myName\folder name
where the last folder has a space in the name, my batch file:
#pyw.exe C:\Users\myName\folder name\mcb.pyw %*
doesn't seem to work properly from the command line. I can now type in
mcb save keyword
into the command line without getting an error, but it's not doing anything. After testing by changing the directory to a folder whose path has no space in it, I've concluded that the problem is because of the space, but I am unsure of how I might go about fixing this.
The second issue is that when the batch file is working, the module shelve seems to be saving the data in the wrong folder. Specifically, I noticed that if I were to run mcb.pyw from the command line, shelve would save the data in C:\Users\myName, which is also the default directory when you open the command windod, instead of the folder C:\Users\myName\folderName, where mcb.pyw and mcb.bat are saved.
I have gotten around this by including the lines:
import os
os.chdir('C:\\Users\\myName\\folderName')
However, is there any other way to solve this issue? Why is shelve saving in C:\Users\myName instead of the folder where everything is already saved?
I apologise if I have made any ettiquette or formatting problems. If you let me know what I did wrong I will do my best to fix it as soon as I can, thank you!
Files are always saved in the current working directory unless they are specified with path names, so you do have to change your working directory if the default one is not what you want.
You can avoid hard-coding the path name and always change your working directory where the script is located with:
import os
import sys
os.chdir(os.path.dirname(sys.argv[0]))
This is my first question.
My python script opens and reads from a present text file using the following simple funct:
open("config.ini", "r")
As this is a relative path it is supposed to work because config.ini is placed in the same directory like the script is when it is launched, that should be the current working dir.
In fact this works perfectly on all of my 3 linux boxes, but I have one user who demands support because he gets an error while opening config.ini. The error raises because
os.path.exists("config.ini")
returns false even if the file is there!
Trying to fix this problem we found out that the only way to make it work is to place config.ini in his home directory despite the supposed working directory is another.
Also, if my script tries to create a file in the present working directory, the file is always created in his home dir instead, and so I think that for some reason his working dir is always home!
How can I troubleshoot this problem? Maybe I could introduce absolute paths, but I am afraid that os.getcwd() would return the homedir instead of the correct one.
Should I maybe suggest this user to fix his machine in some way?
Sorry for this long question but english is not my first language and I am a beginner in coding, so have some difficulties to explain.
Thank you very much in advance! =)
Could it be that the user is executing your script from his home directory?
I.e. suppose the script is in:
/home/user/test/foo/foo.py
But the user calls it thus:
/home/user> python test/foo/foo.py
In this case, the "current directory" the script sees is /home/user.
What you can do is find out the directory the script itself resides in by calling this function:
import os
def script_dir():
return os.path.dirname(os.path.realpath(__file__))
It will always return the directory in which the script lives, not the current directory which may be different. You can then store your configuration file there safely.
Along the same lines as Eli Bendersky's suggestion, you might want to try:
os.path.exists(os.path.join(sys.path[0],"config.ini"))
since sys.path[0] should always be the directory in which the script resides.