Good morning. I am trying to create a "for" loop to search for every file with .txt in a single folder and encrypt them. I was able to successfully do it with a single file but I have been tasked to create a loop to repetitively encrypt multiple files in a single folder
single_encrypt_file.py
from cryptography.fernet import Fernet
file = open('key.key', 'rb')
key = file.read()
file.close()
for filename in os.listdir('testfolder'):
with open(filename, 'rb') as f:
data = f.read()
fernet = Fernet(key)
encrypted = fernet.encrypt(data)
with open(filename, 'wb') as f:
f.write(encrypted)
I am still a beginner in python and programming so it would be great if anyone have ideas on how I should modify my current code. Cheers!
Update: I have modified the code based on the given answer but I am getting an error saying "No such file or directory: testfile.txt" when the file clearly exists when I went to check.
First thing is to do is to find all the file names in the folder. To do that use os.listdir().
Then you simply loop through the filenames:
import os
for filename in os.listdir('dirname'):
##do what you want
Be careful because you might want to check if the folder contains only the files you want to encrypt. Otherwise create an exception to ignore unwanted files
I managed to figure out the problem. turns out os.listdir() method gives you filenames without paths only and as I needed to open files in my current directory (testfolder) I needed to use another which is os.path.join().
single_encrypt_file.py
for filename in os.listdir('testfolder'):
testpath = os.path.join('testfolder', filename)
#run encryption codes
Related
I'm pretty new to programming and I'm currently learning about the open() function used in python. My current goal is to create a to-do list, my first task was to create a filename in read mode otherwise if the file doesn't exist it is to be created in read/write mode "w+".
My current issue is the open() function isn't creating that empty "list.txt" which is the same folder where my code is saved into. I appreciate any feedback :)
def get_list(filename):
try:
f = open(filename, 'r') # try to open the file in read mode
except: # if the file doesn't exist...
f = open(filename, 'w+') # create it by opening it in write
data = f.readlines() # read the content of the file into a list
f.close() # close the file
return data # return data
You're almost there. You have to call the function you created with the Path where you would like the .txt file. The path is the location from the drive where it is stored. The following code is an example of what it should look like.
get_list('C:\Users\jsmith\list.txt')
I need to figure out how to fix this code:
path = "/Folder/Test.txt"
with open(path,"r+") as f:
line = f.readline()
print(line)
It needs to be able to write to the text document "Test.txt" in the folder named "Folder"
First your path should be relative:
path = "./Folder/Test.txt"
if you want to write to a file you need "w" instead of "r" in the open function
Read:
with open(path, "r") as f:
line = f.readline()
print(line)
Write:
with open(path, "w") as f:
f.write("Hello world!")
Using "w" will replace all the current content of the file. If you want to append to the file instead, you should use "a".
path should be in /absolute/location/of/file/filename.
That means either "C:/file/path/you/want/filename" in Windows or "/absolute/path/of/your/file/filename" in *nix
You can also use relative paths if the path you want is nearby (shares a directory, etc.)
For example: if the script is in /user/scripts and you want to save in /user/textfiles/Folder, you can do ../textfiles/Folder
Also make sure that the folder exists, else, it will cause an error as well.
Anyway, as you go further in python, it is recommended that you check out the os module as it can help you a lot with file paths and other things
I have a noob python question... so bear with me.
Can I open multiple files before closing the previos.
So... can I run
import os
files=[]
for file in os.listdir(os.curdir):
files.append(open(file,'w'))
Then edit each file as I want and finish with
for file in files:
file.close()
Thanks in advance
Seems legit and works fine.
Doing operations would be hard for you this way. the list "files" doesn't contain the filenames. You would not know which file is what.
It is perfectly fine to open each file using open and later close all of them. However, you will want to make sure all of your files are closed properly.
Normally, you would do this for one file:
with open(filename,'w') as f:
do_something_with_the_file(f)
# the file is closed here, regardless of what happens
# i.e. even in case of an exception
You could do the same with multiple files:
with open(filename1,'w') as f1, open(filename2,'w') as f2:
do_something_with_the_file(f)
# both files are closed here
Now, if you have N files, you could write your own context manager, but that would probably be an overkill. Instead, I would suggest:
open_files = []
try:
for filename in list_of_filenames:
open_files.append(open(filename, 'w'))
# do something with the files here
finally:
for file in open_files:
file.close()
BTW, your own code deltes the contents of all files in the current directory. I am not sure you wanted that:
for file in os.listdir(os.curdir):
files.append(open(file,'w')) # open(file,'w') empties the file!!!
Maybe you wanted open(file, 'r') or open(file, 'a') instead? (see https://docs.python.org/2/library/functions.html#open)
Your solution will certainly work but the recommended way would be to use contextmanager so that the files gets handled seamlessly. For example
for filename in os.listdir(os.curdir):
with open(filename, 'w') as f:
# do some actions on the file
The with statement will take care of closing the file for you.
My problem is the following:
I want to create a little tool in Python that creates hash values for entered text or from files. I've created all necessary things, GUI, option to select between hash functions, everything is fine.
But when I was testing the program, I realized, that the from files generated hashes aren't the same as the ones given by most download pages. I was confused, downloaded some other hashing tools, they all gave me the same hash as provided on several websites, but my tool always give some other output.
The odd thing is, the hashes generated from "plain text" are in my and in all other tools identical.
The app uses wxPython, but I've extracted my hash function for hash creation from files:
import os, hashlib
path = "C:\file.txt" # Given from some open file dialog, valid file
text = ""
if os.path.isfile(path):
text_file = open(path, "r")
text = text_file.read()
text_file.close()
print hashlib.new("md5", text).hexdigest() # Could be any hash function
Quite simple, but doesn't work as expected.
It seems to work if there's no new line in the file (\n)?
But how to make it work with newline? It's like every file has more than one line.
It is a problem of quoting the backslash character, see https://docs.python.org/2/reference/lexical_analysis.html#literals. Use two backslashes to specify the file name. I would also recommend reading the file in binary mode. As a precaution, print the length of variable text to make sure the file was read.
import os, hashlib
path = "C:\\file.txt" # Given from some open file dialog, valid file
text = ""
if os.path.isfile(path):
text_file = open(path, "rb")
text = text_file.read()
text_file.close()
print len(text)
print hashlib.new("md5", text).hexdigest() # Could be any hash function
Try splitting text update and md5 object creation as below
import hashlib;
md5=hashlib.new('md5')
with open(filepath,'rb') as f:
for line in f:
md5.update(line)
return md5.hexdigest()
I'm trying to use the Python GZIP module to simply uncompress several .gz files in a directory. Note that I do not want to read the files, only uncompress them. After searching this site for a while, I have this code segment, but it does not work:
import gzip
import glob
import os
for file in glob.glob(PATH_TO_FILE + "/*.gz"):
#print file
if os.path.isdir(file) == False:
shutil.copy(file, FILE_DIR)
# uncompress the file
inF = gzip.open(file, 'rb')
s = inF.read()
inF.close()
the .gz files are in the correct location, and I can print the full path + filename with the print command, but the GZIP module isn't getting executed properly. what am I missing?
If you get no error, the gzip module probably is being executed properly, and the file is already getting decompressed.
The precise definition of "decompressed" varies on context:
I do not want to read the files, only uncompress them
The gzip module doesn't work as a desktop archiving program like 7-zip - you can't "uncompress" a file without "reading" it. Note that "reading" (in programming) usually just means "storing (temporarily) in the computer RAM", not "opening the file in the GUI".
What you probably mean by "uncompress" (as in a desktop archiving program) is more precisely described (in programming) as "read a in-memory stream/buffer from a compressed file, and write it to a new file (and possibly delete the compressed file afterwards)"
inF = gzip.open(file, 'rb')
s = inF.read()
inF.close()
With these lines, you're just reading the stream. If you expect a new "uncompressed" file to be created, you just need to write the buffer to a new file:
with open(out_filename, 'wb') as out_file:
out_file.write(s)
If you're dealing with very large files (larger than the amount of your RAM), you'll need to adopt a different approach. But that is the topic for another question.
You're decompressing file into s variable, and do nothing with it. You should stop searching stackoverflow and read at least python tutorial. Seriously.
Anyway, there's several thing wrong with your code:
you need is to STORE the unzipped data in s into some file.
there's no need to copy the actual *.gz files. Because in your code, you're unpacking the original gzip file and not the copy.
you're using file, which is a reserved word, as a variable. This is not
an error, just a very bad practice.
This should probably do what you wanted:
import gzip
import glob
import os
import os.path
for gzip_path in glob.glob(PATH_TO_FILE + "/*.gz"):
if os.path.isdir(gzip_path) == False:
inF = gzip.open(gzip_path, 'rb')
# uncompress the gzip_path INTO THE 's' variable
s = inF.read()
inF.close()
# get gzip filename (without directories)
gzip_fname = os.path.basename(gzip_path)
# get original filename (remove 3 characters from the end: ".gz")
fname = gzip_fname[:-3]
uncompressed_path = os.path.join(FILE_DIR, fname)
# store uncompressed file data from 's' variable
open(uncompressed_path, 'w').write(s)
You should use with to open files and, of course, store the result of reading the compressed file. See gzip documentation:
import gzip
import glob
import os
import os.path
for gzip_path in glob.glob("%s/*.gz" % PATH_TO_FILE):
if not os.path.isdir(gzip_path):
with gzip.open(gzip_path, 'rb') as in_file:
s = in_file.read()
# Now store the uncompressed data
path_to_store = gzip_fname[:-3] # remove the '.gz' from the filename
# store uncompressed file data from 's' variable
with open(path_to_store, 'w') as f:
f.write(s)
Depending on what exactly you want to do, you might want to have a look at tarfile and its 'r:gz' option for opening files.
I was able to resolve this issue by using the subprocess module:
for file in glob.glob(PATH_TO_FILE + "/*.gz"):
if os.path.isdir(file) == False:
shutil.copy(file, FILE_DIR)
# uncompress the file
subprocess.call(["gunzip", FILE_DIR + "/" + os.path.basename(file)])
Since my goal was to simply uncompress the archive, the above code accomplishes this. The archived files are located in a central location, and are copied to a working area, uncompressed, and used in a test case. the GZIP module was too complicated for what I was trying to accomplish.
Thanks for everyone's help. It is much appreciated!
I think there is a much simpler solution than the others presented given the op only wanted to extract all the files in a directory:
import glob
from setuptools import archive_util
for fn in glob.glob('*.gz'):
archive_util.unpack_archive(fn, '.')