I wrote a simple code to find the intersection between two set of ranges and print the intersection. Now i am trying to write the result to a file. but i get an error saying write() argument must be str not set.
import numpy
# initialize A and B
filename = "set.txt"
f = open("set.txt", "w")
x = numpy.arange(4000, 5000, 1)
y = numpy.arange(3500, 5500, 1)
#x.intersection(y)
#print (set(x).intersection(y))
f.write(set(x).intersection(y))
f.close()
it works with print but i include the write it give that error
Your command must be 'str' type:
f.write(str(set(x).intersection(y)))
Related
I faced the module Struct for the first time and my code gives me an error: "unpack requires a buffer of 1486080 bytes"
Here is my code:
def speed_up(n):
source = wave.open('sound.wav', mode='rb')
dest = wave.open('out.wav', mode='wb')
dest.setparams(source.getparams())
frames_count = source.getnframes()
data = struct.unpack("<" + str(frames_count) + "h", source.readframes(frames_count))
new_data = []
for i in range(0, len(data), n):
new_data.append(data[i])
newframes = struct.pack('<' + str(len(new_data)) + 'h', new_data)
dest.writeframes(newframes)
source.close()
dest.close()
How to figure out which format should I use?
The issue in your code is that you're providing struct.unpack with the wrong number of bytes. This is because of your usage of the wave module: Each frame in a wave file has getnchannels() samples, so when calling readframes(n) you will get back n * getnchannels() samples and this is the number you'd have to pass to struct.unpack.
To make your code more robust, you'd also need to look at getsampwidth() and use an appropriate format character, but the vast majority of wave files are 16-bit.
In the comments you also mentioned that the code didn't work after adding print(len(source.readframes(frames_count))). You didn't show the full code but I assume this is because you called readframes twice without calling rewind, so the second call didn't have any more data to return. It would be best to store the result in a variable if you want to use it in multiple lines.
I am trying to apply this code to get the cases I want to measure:
def get_cases(data_dir):
image_folders = os.listdir(data_dir)
image_folders = [f for f in image_f01ders if not f.startswith('.') and '.' not in f]
desired_cases = pd.read_exce1('data/df.xlsm')
desired_cases = desired_cases.query("vetting == 'Y'")
desired_image_ids = desired_cases['ID']
images_to_measure = []
for img in image_folders:
first_ = img.find('.')
if int(img[first_+1]) in desired_image_ids.unique():
images_to_measure.append
images_to_measure = [os.path.join(data_dir, f) for f in images_to_measure]
return images_to_measure
However, when I run this, it throws the following error,
cases = get_cases(data_dir)
File "measure.py", line 70, in get_cases
if int(img[first_+1]) in desired_image_ids.unique():
ValueError: invalid literal for int() with base 10: 'A'
Could someone explain to me why? And how to fix it? Does this have to do with the folder format? or how I find the img files?
the value that img[first_+1] returns is 'A'. it is likely that the number is in base 16. you should pass the number 16 as the 2nd argument to int function. (int(img[first_+1],16)). Doing so will convert the value to an integer from the base 16.
note that if the int function is called without the 2nd argument, it will take the number as a base 10.
if another error comes up, it is possible that something else is wrong.
My assignment is to create an html file of a map. The data has already been given to us. However, when I try to execute my code, I get two errors:
"TypeError: 'str' object cannot be interpreted as an integer"
and
"KeyError: 'Latitude'"
this is the code that I've written:
import folium
import pandas as pd
cuny = pd.read_csv('datafile.csv')
print (cuny)
mapCUNY = folium.Map(location=[40.768731, -73.964915])
for index,row in cuny.iterrows():
lat = row["Latitude"]
lon = row["Longitude"]
name = row["TIME"]
newMarker = folium.Marker([lat,lon], popup=name)
newMarker.add_to(mapCUNY)
out = input('name: ')
mapCUNY.save(outfile = 'out.html')
When I run it, I get all the data in the python shell and then those two errors mentioned above pop up.
Something must have gone wrong, and I'll admit I'm not at all good with this stuff. Could anyone let me know if they spot error(s) or know what I've done wrong?
Generally, "TypeError: 'str' object cannot be interpreted as an integer" can happen when you try to use a string as an integer.
For example:
num_string = "2"
num = num_string+1 # This fails with type error, because num is a string
num = int(num_string) + 1 # This does not fail because num is cast to int
A key error means that the key you are requesting does not exist. Perhaps there is no latitude key, or its misspelled/incorrect capitalization.
I want to write something to a binary file using python.
I am simply doing:
import numpy as np
f = open('binary.file','wb')
i=4
j=5.55
f.write('i'+'j') #where do i specify that i is an integer and j is a double?
g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)
print first, second
The output is just:
[] []
I know it is very easy to do this in Matlab "fwrite(binary.file, i, 'int32');", but I want to do it in python.
You appear to be having some confusion about types in Python.
The expression 'i' + 'j' is adding two strings together. This results in the string ij, which is most likely written to the file as two bytes.
The variable i is already an int. You can write it to a file as a 4-byte integer in a couple of different ways (which also apply to the float j):
Use the struct module as detailed in how to write integer number in particular no of bytes in python ( file writing). Something like this:
import struct
with open('binary.file', 'wb') as f:
f.write(struct.pack("i", i))
You would use the 'd' specifier to write j.
Use the numpy module to do the writing for you, which is especially convenient since you are already using it to read the file. The method ndarray.tofile is made just for this purpose:
i = 4
j = 5.55
with open('binary.file', 'wb') as f:
np.array(i, dtype=np.uint32).tofile(f)
np.array(j, dtype=np.float64).tofile(f)
Note that in both cases I use open as a context manager when writing the file with a with block. This ensures that the file is closed, even if an error occurs during writing.
That's because you are trying to write a string(edited) into a binary file. You also don't close the file before trying to read it again.
If you want to write ints or strings to a binary file try adding the below code:
import numpy as np
import struct
f = open('binary.file','wb')
i = 4
if isinstance(i, int):
f.write(struct.pack('i', i)) # write an int
elif isinstance(i, str):
f.write(i) # write a string
else:
raise TypeError('Can only write str or int')
f.close()
g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)
print first, second
I'll leave it to you to figure out the floating number.
print first, second
[4] []
The more pythonic file handler way:
import numpy as np
import struct
with open ('binary.file','wb') as f:
i = 4
if isinstance(i, int):
f.write(struct.pack('i', i)) # write an int
elif isinstance(i, str):
f.write(i) # write a string
else:
raise TypeError('Can only write str or int')
with open('binary.file','rb') as g:
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)
print first, second
I'm relatively new to python and I'm trying to design a program that takes an input of Binary Data and Converts it to a String of Text. I have the following so far but keep getting the following error: TypeError: unsupported operand type(s) for &: 'str' and 'int' Can anyone see where I'm going wrong? And, if so, advise how to fix it?
a = int(input("please enter the binary you want to convert: "))
for str in a:
g = [~(chr(str)&~240)|(e&~240)]
f = 86
e = 231
d = bin(chr(str))
b = (str)
j=(b)
print(j)
There is quite a lot wrong with what you're doing; I'm not sure how you get the error you claim to have, given the other errors in the posted code. In order of reading the function:
Don't call your own variables str, it prevents you from accessing the built-in of the same name. Also, that variable either isn't a str, or causes a TypeError on chr(str).
You can't iterate over an integer for x in y:; this is also a TypeError.
(The error you report) chr(str) returns a string of length one. This is not a valid operand type for &, hence TypeError.
Another operand, e, has not yet been defined, so that will be a NameError.
Irrespective of that, you never use g again anyway.
Or f - what's that even for?
Now e is defined!
bin(chr(str)) will never work - again, chr returns a string, and bin takes a number as an argument.
b = (str) works, but the parentheses are redundant.
Same with j = (b), which is also not indented far enough to be in the loop.
Neither is print(j).
It is not clear what you are trying to achieve, exactly. If you gave example inputs (what format is the "Binary Data"?) and outputs (and what "String of Text" do you want to get?) along with your actual code and the full error traceback this might be easier.
Edit
With the information provided in your comment, it appears that you are trying to reverse these operations:
a = input("please enter the text you want to hide: ")
for ch in a:
## b = (ch) # this still doesn't do anything!
c = ord(ch)
## d = bin(c) # and d is never used
## e = 231 # e is only used to calculate g
f = 86
## g = (((c&240) >> 4)|(e&240)) # which is also never used
h = (((c&15)|(f&240)))
j = bin(h)
print(j)
This produces, for example (a == 'foo'):
0b1010110
0b1011111
0b1011111
However, to convert the input '0b1010110' to an integer, you need to supply int with the appropriate base:
>>> int('0b1010110', 2)
86
and you can't iterate over the integer. I think you want something like:
data = input("please enter the binary you want to convert: ")
for j in data.split():
h = int(j, 2)
...
where the input would be e.g. '0b1010110 0b1011111 0b1011111', or just do one at a time:
h = int(input(...), 2)
Note that, as the function is reversed, you will have to define f before trying to go back through the bitwise operation.