从字符串中删除特定文本 python3

Remove specific text from a string python3

我有一个使用套接字进行通信的服务器和客户端。服务器需要能够使用命令“grab”(例如,grab text.txt)从客户端下载文件。但是当客户端发回文件名和数据下载时,服务器将文件名解释为名称+数据。

服务器

try:
    conn.send(cmd.encode(ENCODING))
    resp = conn.recv(BUFFER).decode(ENCODING)
except (BrokenPipeError, IOError, TypeError):
    print('The connection is no longer available')

resp_split = resp.split(' ')
if resp_split[0] == 'grab':
    filename1 = resp_split[1:]
    filename = ' '.join([str(elem) for elem in filename1])  #Converts list to str
    filedata1 = resp_split[2:] 
    filedata = ' '.join([str(elem) for elem in filedata1])  #Converts list to str
    f = open(filename,"w+")
    f.write(filedata)
    time.sleep(2)
    f.close()
    print(filename.removesuffix(filedata))

else:
    resp = resp[2:-1]
    print(resp)

客户端

command = sock.recv(COMMMAND_SIZE).decode('utf-8') # Receive command from server.
command_output = 'Invalid command.'
cmd_split = command.split(' ')
if cmd_split[0] == 'grab':
    args1 = cmd_split[1:]
    args = ' '.join([str(elem) for elem in args1])
    try:
        with open(args,'r') as file:
            file_data = "grab " + args + ' ' + file.read()
        command_output = file_data
    except Exception as e:
        print(e)
else:
    command_output = self.exec_windows_cmd(command)
    sock.send(bytes(str(command_output), 'utf-8'))

服务器发送“grab text.txt”,客户端响应“grab text.txt example text 1234”,服务器收到此消息并需要取出 text.txt文件名和文件数据的“示例文本 1234”。相反,它将文件命名为“text.txt example text 1234”并正确地将“example text 1234”放入文件中。

如果你写 resp_split[1:] python 从列表中抓取所有项目,在索引 1 之后并包括索引 1。

但您只想要索引 1 处的项目,因此它应该是:

filename = resp_split[1]