can't get a file size in python - python

I am a python newbie and learning from "automate boring stuff" book, so it says in the book the I can use os.path.getsize(path) to get a file size but when I run this code it gives an error, can you please explain why I am getting this?
import os
mypath = 'C:\\Users\\C2D\\Desktop\\Embedded system\\u1.PNG'
os.chdir(mypath)
print(os.path.getsize(mypath))
error is :
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\C2D\Desktop\Embedded system\u1.PNG'
I am working on windows 8.1 and using python3.8 on pycharm

mypath is a file and not a folder.
With the command os.chdir(mypath) you are trying to change the folder - into an image.
It is generally very important, in which exact line an exception occurs. In this case it will be line 4.
To solve your problem: You can probably just delete this line.

It is failing because of the line os.chdir(mypath). You don't need to chdir().
Assuming the path is correct and the file exists, it should work (print the file size) if you remove the os.chdir() statement.

Related

Problem with path when trying to write a file with a defined name given before by the code in Python

I'm having issues when I try to write a file in Python giving it a certain name and not only pathing it. Here is what I'm trying to do:
page_title=page.find('title')
raw_data_path ='output/'+page_title+'_raw.txt'
print (page_title)
with open(raw_data_path, 'w') as file:
file.write ()
When running this code, I receive the error [Errno 22] Invalid argument: 'output/myfile_raw.txt'
If instead of raw_data_path ='output/'+page_title+'_raw.txt' I put, for example, raw_data_path ='output/'+'_raw.txt' the code works well, so for some reason I can't combine the path with the name I'm trying to give the file.
I've searched that error and I see that it is a routing error, so it might be happening because when I want to add the page_title something happens with the path, but I can't see which is the mistake because it should be working.
Can someone give me some help with this issue?

Parser takes only first character from the filename and says "File not found"

I know it's very difficult to understand my issue, but I'll try my best to explain.
So I've cloned a repository from Github and working on it.
When I run the program without any arguments, it works fine
python main.py --audio works fine.
But when I try to pass my own file, it shows an error.
python main.py --audio myaudio.wav shows an error saying "FileNotFoundError: [Errno 2] No such file or directory: '<File Path/m'"
Notice how it only takes the first character from my argument?
In the code, for default mode, it's something like:
(args.py)parser.add_argument('--audio', default=['default_audio.wav'], type=list) and it works fine.
So naturally, I tried to add '[]' to my file name
python main.py --audio [myaudio.wav] Shows an error too which says "FileNotFoundError: [Errno 2] No such file or directory: '<File Path/['"
See, here it took only the first character of my provided argument i.e. '['
And the file IS there. No spelling mistakes in file name either.
Any help would be very much appreciated.

Python won't create / write to a file

I am new at python and learning the language. The following code should create a file in the running program directory and write to it but it doesn't do this at all in a .py file. If I put the same code in the IDLE shell it returns 17. No errors just doesn't create the file. What am I doing wrong?
with open("st.txt", "w") as f:
f.write("Hi from Python!")
Thanks for the help
Mike
This code is flawless, no problem!
I guess that in your REPL shell, the $PWD environment variable is set for somewhere, so your destination file is in some corner.
No exception thrown indicates that no problem with access authority.
Maybe you can set some absolute path string, such as ~/st.txt
By the way, the successful invoke should return 15 instead of 17, totally count 15 chars.
your code works well, st.txt will be touched at executing path.
other ways, your system account can't write in your execute path.
try in your $HOME path to execute your code, I think, It will work well

Permission Error running through Notepad++

I have a Python 2.7 program that prints a set of data to a text file at the end. The program works perfectly if I import the file into the Pythonshell, but if I attempt to run the script directly from Notepad++ using Crl+R (also using Pythonshell), I get an error:
Traceback (most recent call last):
File "C:\Python27\ZeemanLab.py", line 140, in <module>
with open("Mercury{}at{}A".format(wavelength, B), "w") as f:
IOError: [Errno 13] Permission denied: 'Mercury55at55A'
The problem line:
with open("Mercury{}at{}A".format(wavelength, B), "w") as f:
f.write('A {}nm lamp in a {}A Magnetic field \n'.format(wavelength, B))
I am clueless as to what would make this difference.
Adding and printing the result of os.getcwd() might help you troubleshoot. Perhaps Notepad++ is running the script from a different working directory? Have you tried using an absolute path name like C:\temp\Mercury{}at{}A?
You need to change the permission of the file, or move it to a directory where it has the right privileges.
Under windows 7 english the way to do it is:
Left click on the file
Click properties
Press Security
In "group or user names:", choose your user and click edit.
Set the permerssion to read and write.
If you can't, you might have to change to the Adminster user. However the easiest solution is just to move the folder of your project, and run it in your document, desktop or some other folder.

subprocessing library in Python

import subprocess
sample_file_directory = "..." # directory where file is
SCRIPT_DIR = "..." # directory where script is
p = subprocess.Popen([SCRIPT_DIR,sample_file_directory,'min','edgelen'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
min_side_len, err = p.communicate()
print len(err)
So i have this script that analyzes .ply files (3d file format) and gives me data about the file. I am trying to find out in my directory which files are corrupted and which aren't. So I am trying to use the subprocess library to run the script to find an arbitrary feature of the .ply files (in this case the minimum edge length) If err has anything in it, it means it couldn't retrieve the arbitrary feature and the file is corrupted. Here, I am only running it on one file. However, I keep getting an error.
p = subprocess.Popen([SCRIPT_DIR,sample_file_directory,'min','edgelen'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Can anyone help me figure out why I am getting this error? Both my data directory and script directory are valid. Also, sorry if I left anything out that's important. First time posting.
Is your SCRIPT_DIR variable the absolute path or a relative path valid in the location you're running the script? If it's the latter, it may not work, as the subprocess may start in a different environment that has a different working directory.
The problem lies here:
p = subprocess.Popen([SCRIPT_DIR,sample_file_directory,'min','edgelen'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
Notice this part:
Popen([SCRIPT_DIR,sample_file_directory,'min','edgelen']
Now, see, you already know that subprocess takes a list. But the problem is that you are passing the directory as part of the list. The list is formatted like this:
[command, arg1, arg2...]
Now, when you run that command, you are doing this:
[SCRIPT_DIR -> command
sample_file_directory -> arg1
'min' -> arg2
'edgelen' -> arg3]
See the problem? You are passing the script's directory as the command to run and the script's name as an argument. Import the os module and do this:
p = subprocess.Popen([os.path.join(SCRIPT_DIR,sample_file_directory),'min','edgelen'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
This does this:
[SCRIPT_DIR and sample_file_directory joined together -> command
'min' -> arg1
'edgelen' -> arg2]
os.path.join automatically adds the path separator.
subprocess.Popen() won't combine path components for you. From what I see, you're only providing a directory. You'll need to add the target executable's name to the path being given to Popen. Try the following:
p = subprocess.Popen([os.path.join(SCRIPT_DIR,SCRIPT_NAME),sample_file_directory,'min','edgelen'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
"One other thing it could potentially be is that you're trying to run a 32-bit binary on a 64-bit system without the 32-bit libraries installed. I actually ran into this issue earlier today. A fix is documented here. I don't know anything about your system, so this may be completely irrelevant advice, but I figured it wouldn't hurt to mention it." Dan Albert. He came up with the answer to the solution! Thanks so much Dan!

Categories