如何让python在文本文件中生成新行

2024-10-02 12:27:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如何让python停止在已有文本的地方编写文本?例如,假设文本文件为:

placeholder1
placeholder2
placeholder3
placeholder4
placeholder5

(不带行标签) 现在,当python编写时,它会做类似的事情

placeholder1
placeholder2
placeholder3
placeholder4
placeholder5thethingimtryingtotype

然而,我正试图让它这样做

placeholder1
placeholder2
placeholder3
placeholder4
placeholder5
thethingimtryingtotype 
import socket

import random
localhost =  'localhost'
n = socket.socket()
n.bind((localhost,9999))
n.listen(8)  
while True:
    f = open('C:/Users/myname/Desktop/t.txt', 'r+') 
    b = f.readlines()
    addresses = random.choice(b)
    addresses2 = random.choice(b)
    addresses3 = random.choice(b)            
    addresses4 = random.choice(b)
    addresses5 = random.choice(b)
    addresses6 = random.choice(b)
    addresses7 = random.choice(b)
    addresses8 = random.choice(b)
    c, addr =  n.accept()
    g = list(addr)
    p = str (g.pop(0))
    print("connected with", addr)
    f.writelines(str (p))
    c.send(bytes(str(addresses).strip('/n'), 'utf-8'))
    c.send(bytes(str(addresses2).strip('/n'), 'utf-8'))
    c.send(bytes(str(addresses3).strip('/n'), 'utf-8'))
    c.send(bytes(str(addresses4).strip('/n'), 'utf-8'))
    c.send(bytes(str(addresses5).strip('/n'), 'utf-8'))
    c.send(bytes(str(addresses6).strip('/n'), 'utf-8'))
    c.send(bytes(str(addresses7).strip('/n'), 'utf-8'))
    c.send(bytes(str(addresses8).strip('/n'), 'utf-8'))
    c.send(bytes('if nothing came before this please restart', 'utf-8'))
    c.close()
    f.close()

这是写下连接到“服务器”的IP,这样它就可以将它发送给其他连接的IP,这样他们就可以找到彼此(像某种p2p网络)

使用Python3.10BTW


Tags: 文本sendlocalhostbytesrandomsocketutfaddr

热门问题