Convert multiple base64 to Images in Python - python

I am trying to convert a list of strings to byte64 format so I can decode them and download them as Images. The byte64 format images are stored in file.txt and a snippet of the file is shown below. My attempt only does this for a single byte64 format string, how should I do this for a file containing multiple lines?
snippet from file.txt:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/...
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/...
Here's what I've tried to do:
# read lines from file
f = open("file.txt", "r")
for x in f:
data = f.readlines()
f.close()
# Removing unecessary substrings
images = [w.replace('\n', '') for w in data]
images = [w.replace('data:image/jpeg;base64,', '') for w in images]
# encode string to byte64 format
test = images[1].encode()
# Convert to image
with open("image_1.png", "wb") as fh:
fh.write(base64.decodebytes(test))

If all of your code is working, then it should be as simple as changing the index and file name.
data = []
with open("file.txt", "r") as f
# for x in f: i dont know why this was in a loop
data = f.readlines()
# do this in one line
images = [w.replace('\n', '').replace('data:image/jpeg;base64,', '') for w in data]
for index, base64string in enumerate(images):
test = base64string.encode()
with open("image_{0}.png".format(index), "wb") as fh:
fh.write(base64.decodebytes(test))
I haven't run this code, but it looks like it should work to me.

Related

Slice a given txtfile and write only part of it in a newfile in python

This is my original .txt data:
HKEY_CURRENT_USER\SOFTWARE\7-Zip
HKEY_CURRENT_USER\SOFTWARE\AppDataLow
HKEY_CURRENT_USER\SOFTWARE\Chromium
HKEY_CURRENT_USER\SOFTWARE\Clients
HKEY_CURRENT_USER\SOFTWARE\CodeBlocks
HKEY_CURRENT_USER\SOFTWARE\Discord
HKEY_CURRENT_USER\SOFTWARE\Dropbox
HKEY_CURRENT_USER\SOFTWARE\DropboxUpdate
HKEY_CURRENT_USER\SOFTWARE\ej-technologies
HKEY_CURRENT_USER\SOFTWARE\Evernote
HKEY_CURRENT_USER\SOFTWARE\GNU
And I need to have a new file where the new lines contain only part of those strings, like:
7-Zip
AppDataLow
Chromium
Clients
...
how to do it in python?
Try this:
## read file content as string
with open("file.txt", "r") as file:
string = file.read()
## convert each line to list
lines = string.split("\n")
## write only last part after "\" in each line
with open("new.txt", "w") as file:
for line in lines:
file.write(line.split("\\")[-1] + "\n")
One approach would be to read the entire text file into a Python string. Then use split on each line to find the final path component.
with open('file.txt', 'r') as file:
data = file.read()
lines = re.split(r'\r?\n', data)
output = [x.split("\\")[-1] for x in lines]
# write to file if desired
text = '\n'.join(output)
f_out = open('output.txt', 'w')
f_out.write(text)
f_out.close()

How can i append a text file to order the contents

I have a text file with about 2000 numbers, they are written to the file in a random order...how can i order them from within python? Any help is appreciated
file = open('file.txt', 'w', newline='')
s = (f'{item["Num"]}')
file.write(s + '\n')
file.close()
read = open('file.txt', 'a')
sorted(read)
You need to:
read the contents of the file: open('file.txt', 'r').read().
split the content using a separator: separator.split(contents)
convert each item to a number, otherwise, you won't be able to sort numerically: int(item)
sort the numbers: sorted(list_of_numbers)
Here is a code example, assuming the file is space separated and that the numbers are integers:
import re
file_contents = open("file.txt", "r").read() # read the contents
separator = re.compile(r'\s+', re.MULTILINE) # create a regex separator
numbers = []
for i in separator.split(f): # use the separator
try:
numbers.append(int(i)) # convert to integers and append
except ValueError: # if the item is not an integer, continue
pass
sorted_numbers = sorted(numbers)
You can now append the sorted content to another file:
with open("toappend.txt", "a") as appendable:
appendable.write(" ".join(sorted_numbers)

How to make string from a text file in Python 3?

path = "C:\\Users\\user\\Downloads\\wordlist.txt"
word_list = open(path, 'r')
list = [x for x in word_list.split(" ")]
How can I open a file, so that I can make it into a string and eventually turn that string into a list? I've tried with split(), but it seems that text files can't just be split, although they are read.
Use with open
Ex:
path = "C:\\Users\\user\\Downloads\\wordlist.txt"
l = []
with open(path, "r") as infile: #Read file
for line in infile: #Iterate over each line
l.append(line.split()) #split by space and append
word_list.readlines() will give the list itself as per row ending

Converting the file of decimal values into hex format

I am new to python and I am trying to write a simple script that will convert each row of my .txt file containing decimals into hex format and will save it into another .txt file. My input has the 16 bit values in decimal format such as
15166
46818
26814
640
44756
27831
2646
This is a snippet that I have so far:
import binascii
filename = '1.txt'
content = f.read()
out = binascii.hexlify(content)
f = open('out.txt', 'wb')
f.write(out)
f.close()
This is the output that I am getting 31353136360d0a34363831380d0a32363831340d0a3634300d0a34343735360d0a32373833310d0a323634360d0a393237360d0a323238390d0a333330320d0a33393137370d0a393535340d0a363239310d0a31353438310d0a33353632300d0a35373330310d0a33323933350d0a3834380d0a34313639330d0a33353538340d0a31363936390d0a31313539300d0a31343639350d0a36333931350d0a393238340d0a33323339370d0a343235330d0a33323934320d0a31303139340d0a34393238360d0a34383430370d0a31333330350d0a3336340d0a36323735340d0a32313438310d0a35323734350d0a31303931310d0a34323835380d0a373731370d0a34393530320d0a35313034380d0a36323832330d0a34343833370d0a36313934300d0a33393137310d0a33333032320d0a32333836360d0a36313335360d0a31393038380d0a35393135340d0a36353335320d0a32343233300d0a32303936310d0a34313134330d0a35343433350d0a36343038380d0a35323334340d0a33373136370d0a32363734390d0a36353439300d0a36353236360d0a36313234320d0a33343933360d0a313532360d0a35313236310d0a33353039350d0a36303931350d0a34313336350d0a32333235370d0a333133350d0a33373433380d0a34363837350d0a363831390d0a34373034320d0a31373035380d0a363734350d0a35313135340d0a333535330d0a33343134320d0a36353334360d0a34343334310d0a35333330370d0a35333232320d0a34313336300d0a33383037300d0a32363134350d0a34343532310d0a34373836360d0a34393033360d0a36323037320d0a34373630330d0a34363337300d0a34303534360d0a31393231330d0a373930340d0a393839340d0a31383337350d0a35383231360d0a33353033380d0a31333338310d0a32313637350d0a33383333370d0a35393430340d0a31333933300d0a31353830370d0a33373434370d0a31313832370d0a34383331360d0a32393433350d0a32363831360d0a36313035360d0a34303533350d0a33383335340d0a31373037370d0a34383236360d0a31363237350d0a34343331370d0a35343836320d0a34303730370d0a32363735370d0a32353438380d0a3737320d0a32363038330d0a32373339370d0a35323934380d0a34313537340d0a32363934310d0a3433353539
So I need that each entry will be separated and displayed as a list in my output file. If I do have the line
for c in out:
print(c)
I get the huge list with two decimals in each of it and seemed to be wrong. Please post any solution for this problem.
Another way to do it is using hex like so:
filename = '1.txt'
newfile = '2.txt'
with open(filename, 'r') as f:
numbers = f.read().splitlines()
with open(newfile, 'w') as n:
for num in numbers:
n.write('{}\n'.format(hex(int(num))))

Read text file to list in python

I want to create a text file which contains positive/negative numbers separated by ','.
i want to read this file and put it in data = []. i have written the code below and i think that it works well.
I want to ask if you guys know a better way to do it or if is it well written
thanks all
#!/usr/bin/python
if __name__ == "__main__":
#create new file
fo = open("foo.txt", "w")
fo.write( "111,-222,-333");
fo.close()
#read the file
fo = open("foo.txt", "r")
tmp= []
data = []
count = 0
tmp = fo.read() #read all the file
for i in range(len(tmp)): #len is 11 in this case
if (tmp[i] != ','):
count+=1
else:
data.append(tmp[i-count : i])
count = 0
data.append(tmp[i+1-count : i+1])#append the last -333
print data
fo.close()
You can use split method with a comma as a separator:
fin = open('foo.txt')
for line in fin:
data.extend(line.split(','))
fin.close()
Instead of looping through, you can just use split:
#!/usr/bin/python
if __name__ == "__main__":
#create new file
fo = open("foo.txt", "w")
fo.write( "111,-222,-333");
fo.close()
#read the file
with open('foo.txt', 'r') as file:
data = [line.split(',') for line in file.readlines()]
print(data)
Note that this gives back a list of lists, with each list being from a separate line. In your example you only have one line. If your files will always only have a single line, you can just take the first element, data[0]
To get the whole file content(numbers positive and negative) into list you can use split and splitlines
file_obj = fo.read()#read your content into string
list_numbers = file_obj.replace('\n',',').split(',')#split on ',' and newline
print list_numbers

Categories