I have a file titled "passc" (no .txt, no .py, no extension at all) that contains a single line of code (its a token) similar to:
aABBccDd01234
Yes, there are no quotes or variable assignment in this file
I am trying to import this value into a python script and assign it to a variable (I think it should look something like this):
import passc
code = passc
I have tried variations of the following:
from passc import *
code = passc[0]
And I understand I'm importing a module not a direct object so it shouldn't have a subscriptable element, but I thought I might as well try it.
Without defining the value in "passc" file I can't figure out how to access the value.
Looking for suggestions on how to access this value without altering the "passc" file!
Do not complicate yourself using import passc or from passc import * of this way only we can import files with .py extension.
The fast solution to fix this problem is doing something like this:
# read file
my_file=open("passc","r")
# save code in a var
code = my_file.read()
print(code)
# aABBccDd01234
Cheers!
Related
Files folder containing levels
the import lines
As shown in the second image, in order to import 'level_one', python wanted me to create its own import line,
I tried to import both levels: level_one and level_two, by using the * symbol, which is what you would do to import all methods in a library (I believe this is how it works)
But that doesn't work. The picture below shows me attempting to call out a dictionary I have written in the 'level_two.py' file, but I would need another import statement to make it work.
Where the file is called
Many thanks
It appears you're missing an __init__.py file. You need one in the directory to make python treat the folder as a package.
I have created a python file that consists some data .
I m able to import this data file to a different python file , but my concern is that I can import only one variable at a time and not all the variables at once.
from sourcefilename import RequiredVariable
I want to import and use all the variables in one call . Is that possible.
from sourcefilename import *
This is really not recommended, though. It lets you imports (essentially, execute) any arbitrary code from the module sourcefilename, and then simply copy all global names from that module into your module (overwriting anything previously defined in your module). You should use it only if you can be very certain of the exact data structure that goes into sourcefilename. However, if that is the case, you may as well use a more conventional method for storing data, like JSON or pickle.
Creating Hazel rule that triggers a script when a .mp4 file is dropped in.
Here is the script:
import os
from os import path
from vimeo import VimeoClient
a = "/Path/to/MyVimeoDirectory"
def myfile():
for file in os.listdir("/Path/to/MyVimeoDirectory"):
if file.endswith(".mp4"):
return os.path.join(a, file)
vimeo = VimeoClient("blahblahvimeotoken")
vimeo.upload(myfile)
So basically vimeo.upload() requires a string argument. I've done a ton of research and saw some examples but I can't get them to work for me here. How do I get the resulting path of myfile() to put quotes around the output so I can use it as a string? Thoughts?
In your final line, consider that you are passing myfile as an argument, and not myfile() -- and what the difference is.
A few suggestions: don't use file as the loop variable name since it ghosts the Python file builtin and at the very least makes it confusing to read quickly; Are you sure the loop does what you want? It appears to return just the first appearing .mp4 file from the list of files as os.listdir orders them. myfile does not return all of the .mp4 files.
This probably has an embarrassingly easy answer, but I'm not sure what it is.
In my python code, there is a part where I want to save an array (called "stokes_columns" which is just full of floats) into a text file.
I did this fine with the following:
np.savetxt('../all_pulsars_1400list/%s_1400list.txt' % pname,stokes_columns, delimiter='\t')
The error message I get says:
no such file or directory: '~/all_pulsars_1400list/J0543_1400list.txt'
Where J0543 is the first variable to be used for the '%s'
but - I don't understand because of course there is no file called that - that is the file I am trying to create.
I've double checked the path and it exists.
Is there something obvious I'm doing wrong? Thank you.
You need to expand path to absolute path like this:
>>> import os
>>> os.path.expanduser('~/all_pulsars_1400list/J0543_1400list.txt')
'home/xxx/all_pulsars_1400list/J0543_1400list.txt'
The only way I came up for deleting a file from a zipfile was to create a temporary zipfile without the file to be deleted and then rename it to the original filename.
In python 2.4 the ZipInfo class had an attribute file_offset, so it was possible to create a second zip file and copy the data to other file without decompress/recompressing.
This file_offset is missing in python 2.6, so is there another option than creating another zipfile by uncompressing every file and then recompressing it again?
Is there maybe a direct way of deleting a file in the zipfile, I searched and didn't find anything.
The following snippet worked for me (deletes all *.exe files from a Zip archive):
zin = zipfile.ZipFile ('archive.zip', 'r')
zout = zipfile.ZipFile ('archve_new.zip', 'w')
for item in zin.infolist():
buffer = zin.read(item.filename)
if (item.filename[-4:] != '.exe'):
zout.writestr(item, buffer)
zout.close()
zin.close()
If you read everything into memory, you can eliminate the need for a second file. However, this snippet recompresses everything.
After closer inspection the ZipInfo.header_offset is the offset from the file start. The name is misleading, but the main Zip header is actually stored at the end of the file. My hex editor confirms this.
So the problem you'll run into is the following: You need to delete the directory entry in the main header as well or it will point to a file that doesn't exist anymore. Leaving the main header intact might work if you keep the local header of the file you're deleting as well, but I'm not sure about that. How did you do it with the old module?
Without modifying the main header I get an error "missing X bytes in zipfile" when I open it. This might help you to find out how to modify the main header.
Not very elegant but this is how I did it:
import subprocess
import zipfile
z = zipfile.ZipFile(zip_filename)
files_to_del = filter( lambda f: f.endswith('exe'), z.namelist()]
cmd=['zip', '-d', zip_filename] + files_to_del
subprocess.check_call(cmd)
# reload the modified archive
z = zipfile.ZipFile(zip_filename)
The routine delete_from_zip_file from ruamel.std.zipfile¹ allows you to delete a file based on its full path within the ZIP, or based on (re) patterns. E.g. you can delete all of the .exe files from test.zip using
from ruamel.std.zipfile import delete_from_zip_file
delete_from_zip_file('test.zip', pattern='.*.exe')
(please note the dot before the *).
This works similar to mdm's solution (including the need for recompression), but recreates the ZIP file in memory (using the class InMemZipFile()), overwriting the old file after it is fully read.
¹ Disclaimer: I am the author of that package.
Based on Elias Zamaria comment to the question.
Having read through Python-Issue #51067, I want to give update regarding it.
For today, solution already exists, though it is not approved by Python due to missing Contributor Agreement from the author.
Nevertheless, you can take the code from https://github.com/python/cpython/blob/659eb048cc9cac73c46349eb29845bc5cd630f09/Lib/zipfile.py and create a separate file from it. After that just reference it from your project instead of built-in python library: import myproject.zipfile as zipfile.
Usage:
with zipfile.ZipFile(f"archive.zip", "a") as z:
z.remove(f"firstfile.txt")
I believe it will be included in future python versions. For me it works like a charm for given use case.