Can't write data in text file through Python script - python-3.x

I'm using Python 3.6.4. I'm trying to send the file on a network.
Here is my code. When I try to execute it, it goes to infinite loop and my file remains 0kb.
f = open(f_name+'.txt', 'wb')
while True:
conn, addr = s.accept()
data = conn.recv(1024)
if data == "":
break
f.write(data)
f.close()
print("File closed")
conn.close()

Try something like this where you explicitly return False instead of break. Also, I'd open your connection outside of the while loop to make sure you aren't starting over with pulling data each time.
f = open(f_name+'.txt', 'wb')
conn, addr = s.accept()
while True:
data = conn.recv(1024)
if data != "":
f.write(data)
else:
return False
f.close()
print("File closed")
conn.close()

Related

loop doesn't break up when receiving data from client even i wrote break

Hi everyone I decided to create a program that transfer files between client and server, but the problem is the loop won't break its looks like he's still waiting for data to receive, even I wrote (if not data: break)
I received the file successfully, but it's not back to the outer loop any help and thank you.
while True:
###server side
cmd = input("enter msg command :")
client_socket.send(cmd.encode())
if cmd.startswith("download"):
filename = cmd.strip("download ")
with open(filename, 'wb') as f:
print("Downloading file...")
while True:
data = client_socket.recv(4096)
if not data:
break
f.write(data)
print("Successfully downloaded")`
#####clientside
while True:
command = s.recv(1024)
command = command.decode()
if command.startswith("download"):
print("True\n")
filename = command.strip("download ")
with open(filename,'rb') as f:
print("file sending.....")
while True:
data = f.read(4096)
if not data:
break
s.sendall(data)
print("file has sent")

Subprocess results in "Broken Pipe" error

I'm playing around with socket programming. In the following code snippet I'm trying to connect to client and if his input contains "hack" it will remove it and run shell command and sends back the output.
server side:
import socket
class SP:
def server(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9999))
s.listen(1)
while True:
try:
c, addr = s.accept()
print('Got connection from ', addr)
while True:
data = c.recv(1024)
if data:
if 'hack' in data.decode('utf-8'):
import subprocess
data = data.decode('utf-8')
data = data.strip('hack').lstrip().rstrip()
output = subprocess.call(data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
s.send(str(output).encode('utf-8'))
else:
d = data.decode('utf-8')
print('Got data: '+str(d))
c.send(str('ACK: '+str(d)+' ...').encode('utf-8'))
else:
print('No more data from client: '+str(addr))
break
finally:
s.close()
except Exception as e:
print('Caught Exception: '+str(e))
s.close()
obj = SP()
obj.server()
client-side:
import socket
class CS:
def client(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9999))
while True:
data = input('Enter data to be sent to server: \n')
if not data:
break
else:
s.send(data.encode('utf-8'))
reply = s.recv(1024).decode('utf-8')
print(str(reply))
else:
s.close()
except Exception as e:
print('Caught Exception: '+ str(e))
s.close()
obj = CS()
obj.client()
How can I resolve this the error ? Caught Exception: [Errno 32] Broken pipe doesn't tell me much.
update:
import socket
class SP:
def server(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9999))
s.listen(1)
while True:
try:
c, addr = s.accept()
print('Got connection from ', addr)
while True:
data = c.recv(1024)
if data:
if 'hack' in data.decode('utf-8'):
import subprocess
data = data.decode('utf-8')
data = data.strip('hack').lstrip().rstrip()
print(data)
#output = subprocess.call(data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
s.send(data.encode('utf-8'))
else:
d = data.decode('utf-8')
print('Got data: '+str(d))
c.send(str('ACK: '+str(d)+' ...').encode('utf-8'))
else:
print('No more data from client: '+str(addr))
break
finally:
s.close()
except Exception as e:
print('Caught Exception: '+str(e))
s.close()
obj = SP()
obj.server()
Even when I comment out the line where I call subprocess.call I still get "Broken Pipe" so the error isn't originating from the subprocess call.
You're using server's socket s instead of client's socket c to send the data to the client:
s.send(data.encode('utf-8'))
how about changing it to:
c.send(data.encode('utf-8'))

How do I make my python program to write a new file

I am writing a program by which I can extract data from a file, and then based on some condition, I have to write that data to other files. These files do not exist and only the code will create these new files. I have tried every possible combination of print parameters but nothing is helping. The program seems to run fine with no error in IDLE but no new files are created. Can somebody give me a solution?
Here is my code:
try:
data= open('sketch.txt')
for x in data:
try:
(person, sentence)= x.split(':',1)"""data is in form of sentences with: symbol present"""
man=[] # list to store person
other=[] #list to store sentence
if person=="Man":
man.append(sentence)
elif person=="Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file=open("man_file.txt","w")""" otherman_file and man_file are for storing data"""
otherman_file=open("otherman_file.txt", "w")
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
2 problems
you should use
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
w+ - create file if it doesn't exist and open it in write mode
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file..
https://docs.python.org/2/library/functions.html
2.
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
if sketch.txt file do not exist then "man" and "other" will not initialized
and in the print method will throw another exception
try to run this script
def func():
man = [] # list to store person
other = [] # list to store sentence
try:
data = open('sketch.txt', 'r')
for x in data:
try:
(person, sentence) = x.split(':', 1)
if person == "Man":
man.append(sentence)
elif person == "Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
# print(man, man_file.txt)
# print(other, otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
func()

How to recieve files from a server in python?

I Have made a python script, where you can send files to a remote server and receive them. I can send them to the server but can not seem to retrieve them back I've attached both server and client.py
Server.py
import socket # Import socket module
import os
s = socket.socket()
s.bind(('139.59.173.187', 8010)) # Binds port and IP address
s.listen(3) #wait for client to join
c, addr = s.accept()
def RecvFile():
print ("File is comming ....")
file = c.recv(1024) #recieves file name from client
print(file)
f = open(file,'wb') #open that file or create one
l = c.recv(4096) #now recieves the contents of the file
while (l):
print ("Receiving...File Data")
f.write(l) #save input to file
l = c.recv(4096) #get again until done
print("The file",file,"has been succesfully saved to the server\nConnection from:",addr)
f.close()
def SendFile():
file = c.recv(1024)
print(file)
with open(file,'rb') as f:
c.sendall(f.read())
print("File has been sent to the client:", addr)
main()
def main():
option = str(c.recv(1024), 'utf-8')
print(option)
if option[:1] == "R":
SendFile()
elif option[:2] == "S":
RecvFile()
main()
s.close()
Client.py
import time
import socket
import sys
import urllib.request
#import paramiko
def login():
a = 1
while a == 1:
global user
user = input("Username:")
passw = input("Password:")
with open('User.txt') as f:
for line in f.readlines():
us, pw = line.strip().split("|", 1)
if (user == us) and (passw == pw):
print("login Successful!")
a = a+1
main()
return
print("Incorrect details, Try again!")
def register():
print("You will recieve a generated Username from your Name and age")
regName = input("First Name: ")
regAge = input("Age: ")
regPass = input("Password: ")
regUser = (regName[0:3]+regAge)
with open('User.txt', 'a') as file:
file.writelines(regUser+"|"+regPass+"\n")
print("You have Succesfully registered")
print("Your Username is:"+regUser)
print("Your Password is:"+regPass)
print("!Please keep these credentials secure!")
def main():
print("=========================Welcome to Bluetooth Projector=========================")
option = input("Here are your options:\n--> Press C to connect to the projector\n--> Press F for File System")
x = 1
while x == 1:
if option == "C" or option == "c":
optionc(x)
elif option == "F" or "f":
File_System()
def optionc():
print("Loading.....")
time.sleep(2)
print("Obtaining IP addres.....")
time.sleep(2)
print("Connecting.....")
time.sleep(3)
print("Connected")
x = x+1
def File_System():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('139.59.173.187',8010))
print("=========================Welcome to the File System =========================")
option = input("Here are your options:\n--> Press S to upload files\n--> Press R to retrieve files")
if option == "S" or option == "s":
s.send("S".encode('utf-8'))
file_name = input("Please input the file name\n>>>")
name = input("What would you like it to be saved as?\n>>>")
s.send(name.encode('utf-8'))
with open(file_name,'rb') as f:
s.sendall(f.read())
print("File has been sent to the server")
main()
elif option == "R" or option == "r":
s.send("R".encode('utf-8'))
filename = input("What is the filename you wish to recieve\n>>>")
s.send(filename.encode('utf-8'))
print ("File is comming ....")
f = open(filename,'wb') #open that file or create one
l = s.recv(1024) #now recieves the contents of the file
while (l):
print ("Receiving...File Data")
f.write(l) #save input to file
l = s.recv(1024)
print("The file",filename,"has been succesfully saved to your computer")
f.close()
while True:
check = input("Do you already have an account? Y/N \n ")
if check == "Y" or check == "y":
login()
break
elif check == "N" or check == "n":
register()
break
else:
print("pleae enter either Y or N")
Please look at the Filesystem() in the client file. I think it is receiving the second wave of bytes when getting files that is the problem
an was error is either broken pipe which I fixed.
But now the actually receiving file loop doesn't go through and stops getting the file bytes. I believe this is my error. I am confused however since my code is pretty much identical to sending the file to the server which has no complications.
But now the actually receiving file loop doesn't go through and stops getting the file bytes. I believe this is my error.
You are right. The client gets no indication that there aren't more file contents to come, and thus keeps on waiting in recv forever. To rectify this, you can let the server shut down the connection when the file has been sent, or, if you want the connection to be kept, inform the client about when it has to stop receiving, e. g. by sending it the file length beforehand.

Send and recieve files in python

So, I am making something in my computer science class where you can send files to a remote server and that works, but cant recv them back.
SERVER.PY
import socket # Import socket module
import os #imports os module
def RecvFile():
while True: # allows it to always save files and not have to be restarted.
c, addr = s.accept()
print ('Connection Accepted From',addr)# this prints out connection and port
print ("File is comming ....")
file = c.recv(1024) #recieves file name from client
f = open(file,'wb') #open that file or create one
l = c.recv(1024) #now recieves the contents of the file
while (l):
print ("Receiving...File Data")
f.write(l) #save input to file
l = c.recv(1024) #get again until done
print("The file",file,"has been succesfully saved to the server\nConnection from:",addr)
f.close()
def SendFile():
c, addr = s.accept()
print("Connection Accepted From",addr)
filename = c.recv(1024)
if os.path.isfile(filename):
s.send("EXISTS"+str(os.pthat.getsize(filename)))
response = c.recv(1024)
if response[:2] == 'OK':
with open(filename, 'rb') as f:
s.sendall(f.read)
f.close()
else:
s.send("ERR")
s.close()
def main():
s = socket.socket()
s.bind(('139.59.173.187', 8000)) # Binds port and IP address
s.listen(3)
print("Server Started")
while True:
c, addr = s.accept()
option = c.recv(1024)
if option == "S":
RecvFile()
elif option == "R":
SendFile()
else:
s.send("Incorrect input".encode('utf-8'))
main()
#if errors occur
c.close()
I think the server.py is the problem
Client .py
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('139.59.173.187',8000))
print("=========================Welcome to the File System =========================")
option = input("Here are your options:\n--> Press S to upload files\n--> Press R to retrieve files")
if option == "S" or option == "s":
s.send("S".encode('utf-8'))
file_name = input("Please input the file name\n>>>")
name = input("What would you like it to be saved as?\n>>>")
s.send(name.encode('utf-8'))
with open(file_name,'rb') as f:
s.sendall(f.read())
print("File has been sent to the server")
main()
elif option == "R" or option == "r":
s.send("R".encode('utf-8'))
filename = input("What is the filename you wish to recieve\n>>>")
s.send(filename.encode('utf-8'))
print ("File is comming ....")
f = open(filename,'wb') #open that file or create one
l = c.recv(1024) #now recieves the contents of the file
while (l):
print ("Receiving...File Data")
f.write(l) #save input to file
l = c.recv(1024) #get again until done
print("The file",filename,"has been succesfully saved to your computer")
f.close()
I have put 7 hours into learning this and the asignment is due in friday. rather than saying the code could you comment how it works etc.
In server.py, SendFile and RecvFile both use a socket object s that they have no access to. I recommend that you pass it as an argument :
def RecvFile(s):
#...
def SendFile(s):
#...
And then in main :
if option == "S":
RecvFile(s)
elif option == "R":
SendFile(s)

Resources