I have created a text file of randomly generated words, now i would like to write a script that can use that data to create sha256 hashes from those words...would prefer for hashes to be saved as a .txt file also, but in my failed attempt here I was simply trying to print them out. Any suggestions?
#!usr/bin/python
# Filename: doesnt_work
import os
import hashlib
with open("wordlist.txt","r") as f:
for line in f:
line = line.rstrip("\n")
m = sha256(line)
print(m.hexdigest())
Although you should have posted the exception, I'm guessing this would fix it
m = hashlib.sha256(line)
And there is an indentation problem
#!usr/bin/python
# Filename: doesnt_work
import os
import hashlib
with open("wl.txt","r") as f:
for line in f.readlines():
line = line.rstrip("\n")
m = hashlib.sha256(line)
print(m.hexdigest())
Related
I would like assign a file to sys.stdin so that I can read contents of the file with input(). The code below runs as expected as script but it is problematic when it is written in notebook. After calling function input() it shows me an input textbook, which I do not want since I reassigned stdin to a file. So, I expect that the line in the file would be read instead.
import sys
file = open("input.in")
sys.stdin = file
val = input()
print(val)
It seems to me notebook ignores sys.stdin. I couldn't find why this is happening and how to fix it.
Thanks.
Update
I end up with overriding input function. It will do the job but I leave question open to see if someone has a better solution.
file = open("input.in")
input = file.readline
You can read the file to an in-memory buffer and then direct stdin to read from that. For example, to redisplay a file
import sys
import io # in python2, import StringIO
input_file = open('myfile.txt', 'r')
sys.stdin = io.StringIO(input_file.read())
for line in sys.stdin:
print(line, end='')
For your purpose, you may want
import sys
import io # in python2, import StringIO
input_file = open('myfile.txt', 'r')
sys.stdin = io.StringIO(input_file.read())
val = sys.stdin.readline()
# Rest of program using val
I am writing a program where it asks you what text file the user wants to read then it begins to read whatever file name the user inputs. Here is what I have so far:
import sys
import os
import re
#CHOOSE FILE
print "Welcome to the Parsing Database"
raw_input=raw_input("enter file name to parse: ")
#ASSIGN HEADERS AND SEQUENCES
f=open("raw_input", "r")
header=[]
sequence=[]
string=""
for line in f:
if ">" in line and string=="":
header.append(line[:-2])
elif ">" in line and string!="":
sequence.append(string)
header.append(line[:-2])
string=""
else:
string=string+line[:-2]
sequence.append(string)
The first two lines work but then it says it cannot find the file that I inputted to read. Please help! Thanks.
Off the top of my head, I think that f = open("raw_input", "r") needs to be f=open(raw_input, "r"), because you are trying to reference the string contained in the variable raw_input, as opposed to trying to open a file named raw_input. Also you should probably change the name of the variable to something more readable, because raw_input() is a function used in your code as well as a variable, which makes it hard to read. Are there any other specific problems you are having with your code?
f=open("raw_input", "r")
"raw_input" is a plain string. You have to referente to it as raw_input.
Also, there's no lines if you don't use .read() with open() method so you can't parse them. Read lines from a file given from raw_input can be done doing that:
import sys
import os
import re
#CHOOSE FILE
print "Welcome to the Parsing Database"
raw_input_file=raw_input("enter file name to parse: ")
#ASSIGN HEADERS AND SEQUENCES
testfile = open(raw_input_file, "r")
secuence = []
for line in testfile.read().splitlines():
secuence.append(line)
for i in secuence:
print i
testfile.close()
I've been trying to make my python code to fill a form in word with data that i scraped off the Internet. I wrote the data in a txt file and are now trying to fill the word file with this code:
import zipfile
import os
import tempfile
import shutil
import codecs
def getXml(docxFilename,ReplaceText):
zip = zipfile.ZipFile(open(docxFilename,"rb"))
xmlString= zip.read("word/document.xml")
for key in ReplaceText.keys():
xmlString = xmlString.replace(str(key), str(ReplaceText.get(key)))
return xmlString
def createNewDocx(originalDocx,xmlString,newFilename):
tmpDir = tempfile.mkdtemp()
zip = zipfile.ZipFile(open(originalDocx,"rb"))
zip.extractall(tmpDir)
#3tmpDir=tmpDir.decode("utf-8")
with open(os.path.join(tmpDir,"word/document.xml"),"w") as f:
f.write(xmlString)
filenames = zip.namelist()
zipCopyFilename = newFilename
with zipfile.ZipFile(zipCopyFilename,"w") as docx:
for filename in filenames:
docx.write(os.path.join(tmpDir,filename),filename)
shutil.rmtree(tmpDir)
f=open('test.txt', 'r',)
text=f.read().split("\n")
print text[1]
Pavarde = text[1]
Replace = {"PAVARDE1":Pavarde}
createNewDocx("test.docx",getXml("test.docx",Replace),"test2.docx")
The file is created but I cant open it.
I get the following error:
Illegal xlm character
My guess would be that theres something with the encoding but I cant find a solution.
I am trying to generate hashes of files using hashlib inside Tkinter modules.
My goal:
Step 1:- Button (clicked), opens up a browser (click file you want a hash of).
Step 2:- Once file is chosen, choose output file (.txt) where the hash will be 'printed'.
Step 3:- Repeat and have no clashes.
from tkinter.filedialog import askopenfilename
import hashlib
def hashing():
hash = askopenfilename(title="Select file for Hashing")
savename = askopenfilename(title="Select output")
outputhash = open(savename, "w")
hash1 = open(hash, "r")
h = hashlib.md5()
print(h.hexdigest(), file=outputhash)
love.flush()
It 'works' to some extent, it allows an input file and output file to be selected. It prints the hash into the output file.
HOWEVER - If i choose ANY different file, i get the same hash everytime.
Im new to Python and its really stumping me.
Thanks in advance.
Thanks for all your comments.
I figured the problem and this is my new code:
from tkinter.filedialog import askopenfilename
import hashlib
def hashing():
hash = askopenfilename(title="Select file for Hashing")
savename = askopenfilename(title="Select output")
outputhash = open(savename, "w")
curfile = open(hash, "rb")
hasher = hashlib.md5()
buf = curfile.read()
hasher.update(buf)
print(hasher.hexdigest(), file=outputhash)
outputhash.flush()
This code works, You guys rock. :)
In your case you do the digest of the empty string and probably you get:
d41d8cd98f00b204e9800998ecf8427e
I used this method to digest, that is better for big files (see here).
md5 = hashlib.md5()
with open(File, "rb") as f:
for block in iter(lambda: f.read(128), ""):
md5.update(block)
print(md5.hexdigest())
A very simple way
from hashlib import md5
f=open("file.txt","r")
data=f.read()
f.close()
Hash=md5(data).hexdigest()
out=open("out.txt","w")
out.write(Hash)
out.close()
I'am new to Python 3 and could really use a little help. I have a txt file containing:
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=D:\somewhere
FriendlyName=something
I have a python script that in the end, should change just two lines to:
TargetName=D:\new
FriendlyName=Big
Could anyone help me, please? I have tried to search for it, but I didnt find something I could use. The text that should be replaced could have different length.
import fileinput
for line in fileinput.FileInput("file",inplace=1):
sline=line.strip().split("=")
if sline[0].startswith("TargetName"):
sline[1]="new.txt"
elif sline[0].startswith("FriendlyName"):
sline[1]="big"
line='='.join(sline)
print(line)
A very simple solution for what you're doing:
#!/usr/bin/python
import re
import sys
for line in open(sys.argv[1],'r').readlines():
line = re.sub(r'TargetName=.+',r'TargetName=D:\\new', line)
line = re.sub(r'FriendlyName=.+',r'FriendlyName=big', line)
print line,
You would invoke this from the command line as ./test.py myfile.txt > output.txt
Writing to a temporary file and the renaming is the best way to make sure you won't get a damaged file if something goes wrong
import os
from tempfile import NamedTemporaryFile
fname = "lines.txt"
with open(fname) as fin, NamedTemporaryFile(dir='.', delete=False) as fout:
for line in fin:
if line.startswith("TargetName="):
line = "TargetName=D:\\new\n"
elif line.startswith("FriendlyName"):
line = "FriendlyName=Big\n"
fout.write(line.encode('utf8'))
os.rename(fout.name, fname)
Is this a config (.ini) file you're trying to parse? The format looks suspiciously similar, except without a header section. You can use configparser, though it may add extra space around the "=" sign (i.e. "TargetName=D:\new" vs. "TargetName = D:\new"), but if those changes don't matter to you, using configparser is way easier and less error-prone than trying to parse it by hand every time.
txt (ini) file:
[section name]
FinishMessage=
TargetName=D:\something
FriendlyName=something
Code:
import sys
from configparser import SafeConfigParser
def main():
cp = SafeConfigParser()
cp.optionxform = str # Preserves case sensitivity
cp.readfp(open(sys.argv[1], 'r'))
section = 'section name'
options = {'TargetName': r'D:\new',
'FriendlyName': 'Big'}
for option, value in options.items():
cp.set(section, option, value)
cp.write(open(sys.argv[1], 'w'))
if __name__ == '__main__':
main()
txt (ini) file (after):
[section name]
FinishMessage =
TargetName = D:\new
FriendlyName = Big
subs_names.py script works both Python 2.6+ and Python 3.x:
#!/usr/bin/env python
from __future__ import print_function
import sys, fileinput
# here goes new values
substitions = dict(TargetName=r"D:\new", FriendlyName="Big")
inplace = '-i' in sys.argv # make substitions inplace
if inplace:
sys.argv.remove('-i')
for line in fileinput.input(inplace=inplace):
name, sep, value = line.partition("=")
if name in substitions:
print(name, sep, substitions[name], sep='')
else:
print(line, end='')
Example:
$ python3.1 subs_names.py input.txt
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=D:\new
FriendlyName=Big
If you are satisfied with the output then add -i parameter to make changes inplace:
$ python3.1 subs_names.py -i input.txt