TypeError: a bytes-like object is required, not 'str' when writing to a file in Python 3
You opened the file in binary mode:
with open(fname, 'rb') as f:
This means that all data read from the file is returned as bytes
objects, not str
. You cannot then use a string in a containment test:
if 'some-pattern' in tmp: continue
You'd have to use a bytes
object to test against tmp
instead:
if b'some-pattern' in tmp: continue
or open the file as a textfile instead by replacing the 'rb'
mode with 'r'
.
TypeError: a bytes-like object is required, not 'str' when I'm inputting command in console
This error is because python expects bytes not string to be sent via socket.
Hence you have to convert strings to bytes before sending that. you can use encode()
to convert string to bytes and use decode()
to convert bytes received into string.
I have updated your code, Please refer below, this should work fine.
import socket
HOST = '0.0.0.0'
PORT = 12345
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
print("\n[*] Listening on port " +str(PORT)+ ", waiting for connexions. ")
client_socket, (client_ip, client_port) = server_socket.accept()
print("[*] Client " +client_ip+ " connected \n")
while True:
try:
command = input(client_ip+ ">")
if(len(command.split()) != 0):
client_socket.send(command.encode('utf-8')) #Encoding required here
else:
continue
except(EOFError):
print("Invalid input, type 'help' to get a list of implented commands. \n")
continue
if(command == "quit"):
break
data = client_socket.recv(1024)
print(data.decode('utf-8') + "\n") #Decoding required here
client_socket.close()
TypeError: a bytes-like object is required, not 'str' when trying to write in csv file
The csv
module is one of the pieces where the conversion Python2 -> Python3 is not really straightforward. The underlying file is expected to be opened as text and no longer as a binary file, but with empty end of lines.
So I would write:
with open('C:/path_to_csv_file/fold1_1.csv', 'w', newline='', encoding='utf-8') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row, timeseq in izip(fold1, fold1_t):
spamwriter.writerow([s +'#{}'.format(t) for s, t in izip(row, timeseq)])
The current error is caused by the csv module sending a unicode string while the undelying file expected bytes.
python ftplib TypeError: a bytes-like object is required, not 'str'
When you are opening f on line 107, try 'rb' instead of 'r'
That may be sufficient to do the trick.
For SFTP in the past, I've used paramiko. A code snip is below:
import paramiko
def sendFile(**kwargs):
trans = paramiko.Transport(kwargs['host'], kwargs['port'])
trans.connect(username = kwargs['username'], password = kwargs['password'])
conn = paramiko.SFTPClient.from_transport(trans)
conn.put(sourceFile, destFile)
I've severely redacted the above to get basics across.
(From experience) I'd recommend you do the following as part of a wider solution:
- Copy your original source file and rename as a .partial file or similar (to prevent changes to source mid transfer)
- Check remote (dest) area for existence of similar file before trying to copy, delete if its older or different size, abandon transfer if same
- Transfer the .partial file
- Check that the .partial file at dest is same as source (checksums)
5a. If same, remove the .partial from destFile
5b. If not same, repeat transfer - When transfer success, delete the .partial file from source area
TypeError: a bytes-like object is required, not 'str', for writing string to file
In your comment you said that you were opening the file as a bytes by using the argument wb
however you're trying to write a string
to the file which causes the error.
To fix that all you have to do is convert the string to bytes
for d in range(0,d2.size):
c2 += str(d2.item(d))
cf.write(bytes(chr(int(c2,2)), 'utf-8'))
TypeError a bytes-like object is required, not 'str' (Pydub)
Error message seems pretty straightforward : AudioSegment
class constructor is expecting a bytes object and you are passing a String instead.
According to the pydub doc, you could simply call from_wav()
method by passing your filepath as a string.
Example (from the doc) :
song = AudioSegment.from_wav("never_gonna_give_you_up.wav")
Related Topics
Difference Between Map, Applymap and Apply Methods in Pandas
Typeerror: Method() Takes 1 Positional Argument But 2 Were Given
How to Create a Daemon in Python
Django Template How to Look Up a Dictionary Value With a Variable
Do Regular Expressions from the Re Module Support Word Boundaries (\B)
How Are Python'S Built in Dictionaries Implemented
Count the Frequency That a Value Occurs in a Dataframe Column
When Is "I += X" Different from "I = I + X" in Python
How to Open a Chrome Profile Through Python
Filter Dataframe Rows If Value in Column Is in a Set List of Values
Read Subprocess Stdout Line by Line
How to Convert an Integer to a String in Any Base
How to Safely Create a Nested Directory