Search code examples
pythonstringfilerebuild

Convert file into string then Rebuild that String and make it a file again


I want to send files over the network, however all the tools and commands that was proposed to me wont allow me to automate the process.

Now I remember there's a function in java which allows you to convert the file into json base64 string, then this string will be sent over the network, then the machine that will receive this will rebuild this into file.

I wonder if I could do that kind of stuff in python?

Any ideas? Thanks!


Solution

  • well, reading a file and writing a file are easy:

    #read from a file
    with open("path/to/file", "rb") as read_file:
        contents = read_file.read()
    #write to a file
    with open("path/to/file", "wb") as write_file:
        write_file.write(contents)
    

    and for base64 encoding, look at the python docs

    sending data over a connection is simple enough, and you can do it in many methods - i am not going to solve it here, but i will give you a list of methods you can use:

    here is an example using socket from http://wiki.python.org/moin/TcpCommunication

    import socket
    
    TCP_IP = '127.0.0.1'
    TCP_PORT = 5005
    BUFFER_SIZE = 1024
    MESSAGE = "Hello, World!"
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, TCP_PORT))
    s.send(MESSAGE)
    data = s.recv(BUFFER_SIZE)
    s.close()
    
    print "received data:", data