How to update a binary file? - python

I am reading file in binary mode using python and it is working perfectly. I tried to update the content and the save it into a new file. The code's below:
def main():
f = open("inputFile", "rb")
myFile = f.read()
outFile = myFile
for i in range(0, len(myFile)):
d1 = myFile[i] + 1
outFile[i] = d1
f2 = open("otFile", "wb")
f2.write(outFile)
f2.close()
The error is:
outFile[i] = d1
TypeError: 'bytes' object does not support item assignment
I tried
outFile[i] = bytes(d1)
I've got this error:
TypeError: 'bytes' object does not support item assignment

Use bytearray() to convert the infile which gives the functionality of both reading and writing as well
def main():
f = open("infile", "rb")
myFile = f.read()
outFile = bytearray(myFile)
for i in range(0, len(myFile)):
d1 = myFile[i] + 1
outFile[i] = d1
f2 = open("outfile", "wb")
f2.write(outFile)
f2.close()

I think you can just to something like this:
def main():
f = open("inputFile", "rb")
myFile = f.read()
f.close()
outFile = myFile
for i in range(0, len(myFile)):
d1 = myFile[i] + 1
outFile += bytes(d1)
f2 = open("otFile", "wb")
f2.write(outFile)
f2.close()
main()

Related

How to auto read file without input, while ability to input when necessary. PYTHON

while 1:
f = open('list.txt', mode='r')
print(f.read())
f.close()
f = open('list.txt', mode='a')
with open("list.txt",'a',encoding = 'utf-8') as f:
x = input('message: ')
f.write(f'| {name}: {x}\n')
f.close()
I need to be able to print(f.read()) every second, while still being able to get the value of x whenever. How?

Trying to remove null bytes but deleting all my text

So I'm trying to remove null bytes from some text.
I wrote three functions that I think do the same thing.
They all end up giving me blank files and erasing all input.
Here is the example input with a null byte:
T: 14/01/2015 22:27:05**\00**||||END_OF_RECORD <- ** so you can see it (I can see it in my ubuntu text editor)
T: 14/01/2015 22:27:05 ||||END_OF_RECORD <- what my IDE shows is a box there
Here is the code I wrote to try and fix the files, but they just end up blank.
from pathlib import Path
# Removes null bytes from the txt files
def removeNULLBytes():
for p in workspace.glob('*.csv'):
new = Path(workspace, p.name)
new = new.with_suffix('.csv')
with p.open() as infile, new.open('wb') as outfile:
fileName = infile.name
with open(fileName, 'rb') as in_file:
data = in_file.read()
# data = str(data, encoding='utf8', errors='ignore')
data = (data.replace(b'\x00', b''))
outfile.write(data)
def removeNULLs():
for p in workspace.glob('*.csv'):
new = Path(workspace, p.name)
new = new.with_suffix('.csv')
with p.open() as infile, new.open('w') as outfile:
fileName = infile.name
with open(fileName, 'r') as in_file:
data = in_file.read()
# data = str(data, encoding='utf8', errors='ignore')
data = (data.replace(u"\u0000", ""))
outfile.write(data)
def removeNull():
for p in workspace.glob('*.csv'):
new = Path(workspace, p.name)
new = new.with_suffix('.csv')
with p.open() as infile, new.open('w') as outfile:
for line in infile.read():
newline = ''.join([i if not u"\u0000" else "" for i in line])
data = (line.replace(line, newline))
outfile.writelines(data)
if __name__ == '__main__':
workspace = Path('/home/')
# removeNULLBytes()
removeNull()
# removeNULLs()
Any advice is much appreciated. Thanks!

python 3.6: Error: a bytes-like object is required, not 'str' when reading a file

I am trying read a file with following code.
filenames = os.listdir(path)
data = []
for file in filenames:
file_path = os.path.join(path, file)
print (file_path)
with open(file_path, 'r') as f:
try:
soundId = os.path.splitext(file)[0]
print (soundId)
content = f.read()
pp = pickle.loads(content)
pp = np.asarray(pp)
data[soundId] = pp
except Exception as e:
print ("Error occurred" + str(e))
when i run the code it give me
Error occurreda bytes-like object is required, not 'str'
The error occurs at the line pp = pickle.loads(content)
There are other questions with similar issue but none of them helped.
I am trying to read a melspectogram data of audio file.
Sample file i am trying to read
How do i fix this?
with open(file_path, 'rb') as f: instead of with open(file_path, 'r') as f:
or use content.encode() for explicit bytes conversion.
Update
Your question is related to how-load-cv2-keypoint-and-descriptors-correctly-on-opencv-3-with-python-3
Use below code , it should work:
# blues.00000.pp
import pickle, numpy as np
pp_list = np.fromfile('blues.00000.pp')
print('pp_list type :' + str(type(pp_list)))
pp = []
data = dict()
soundID = 'ppFile1'
for i in range(len(pp_list)):
temp = pp_list[i] * 1
pp.append(temp)
pp = np.asarray(pp)
print('pp data : ' + str(pp))
data[soundID] = pp
print('ppdata dic :' + str(data))
Output
pp_list type :<class 'numpy.ndarray'>
pp data : [4.56259939e+257 4.78104776e+180 9.28824150e+242 ... 1.00603813e+165
6.01326204e-067 1.55998657e-259]
ppdata dic :{'ppFile1': array([4.56259939e+257, 4.78104776e+180, 9.28824150e+242, ...,
1.00603813e+165, 6.01326204e-067, 1.55998657e-259])}

Save/load function in Python

I have to create a save function and a load function that saves a dictionary in the format of:
123;Kalle;
123;Maria;
321;Anna;
321;Olle;
My dictionary is supposed to look like a phonebook, with the key being the name and the value is the phonenumber:
telebook = {"jacob":"8472923777", "nisse":"092563243"}
How can I write a function that saves my phonebook in the format mentioned? It should look like this:
8472923777;jacob;
This is my current code:
def save(lista, telebook):
import pickle
filename = lista[1]
f = open(filename, "w")
pickle.dump(telebook, f)
f.close()
print telebook
def load(lista, telebook):
import pickle
try:
filename = lista[1]
f = open(filename, "r")
telebook_1 = pickle.load( f )
telebook.clear()
telebook.update(telebook_1)
f.close()
print telebook
except:
print "This file doesn't exist"
EDIT:
My save function was easier than I thought, managed to solve it on my own. Not sure how to get the load function to work though.
book = raw_input("telebook> ").lower()
lista = book.split()
def save(lista, telebook):
filename = lista[1]
f = open(filename, "w")
for name, num in telebook.items():
f.write(num+";"+name+";"+"\n")
f.close()
print telebook
My load is the same as before but obviously I can't use that one anymore.
def save(telebok, filepath):
with open(filepath, 'w') as outfile:
for name,num in telebok.items():
outfile.write("{};{};\n".format(num, name))
And to get it back:
import csv
def load(filepath):
with open(filepath) as infile:
telebok = dict((v,k) for v,k,_ in csv.reader(infile, delimiter=';'))
return telebok

printing data from a json file to csv file

when i m printing data from my json file to csv file it is not getting printed in diff columns..
here is my code
import json
import urllib
import csv
def main():
f1 = open('tweet-stream.json','r')
Outputfile =open('newdata3.csv', 'w')
count = 0
for line in f1:
d = json.loads(line)
lang = d["user"]["lang"]
status_count = d["user"]["statuses_count"]
print >>Outputfile,"Language: " + lang + "Status_Count" +str(status_count)
if __name__ == "__main__":
main()
f1 = json.load(open(tweet-stream.json', 'r'))
fileWriter = csv.writer(file1 , delimiter=",",quotechar='"', quoting=csv.QUOTE_MINIMAL)
for x in f1:
temp = [x["user"]["lang"],x["user"]["statuses_count"]]
fileWriter.writerow(temp)
file1.close()

Categories