【问题标题】:Delete the first x character in a file with python [closed]用python删除文件中的第一个x字符[关闭]
【发布时间】:2019-04-30 13:05:11
【问题描述】:

我正在编写一个程序。但我有一个问题。

我想从文件中删除第一个 x 字符。

msg = clientsocket.recv(1024)
    if len(msg) < 2:
      print "Exit"
      break
    try:
      myfile = open('logs/demo.txt','a')
      msg = msg.replace('\n','')
      msg = msg.replace(' ','')
      myfile.write(msg)
      myfile.flush()
      myfile.close() 
    except IOError:
      print "write error"
    finally:
      myfile.close()
    try:

      myfile.close()
      myfile=open("logs/demo.txt","r+")
      firstdata=myfile.read()  
      firstdata.replace('\n','')
      firstdata.replace(' ','')

      son = firstdata.rfind("#")
      firstdata = firstdata[:son]
      print firstdata
      #os.remove("logs/demo.txt")
      myfile.close()
      os.remove("logs/demo.txt")

      myfile = open('logs/demo.txt','a')
      firstdata = firstdata.replace('\n','')
      firstdata = firstdata.replace(' ','')
      myfile.write(firstdata[son:])
      myfile.flush()
      myfile.close() 

    except IOError:
      print "read error"
    finally:
      myfile.close()

这段代码太长,我打开文件3次。

我想要:

删除前:

    In file : "asdfghjkl#mnbvc#qwerty#poiuyt"

删除后:

    In file : "poiuyt"

【问题讨论】:

    标签: python python-2.7 file


    【解决方案1】:

    如果要从 x 为整数的文件中删除前 x 个字符(在本例中为 23),则

    with open("logs/demo-out.txt","w") as output:
        with open("logs/demo.txt","r") as input:
            output.write(input.read()[23:])
    

    就地更新文本文件(最后添加内容除外)需要 (1) 将数据读入内存,关闭文件,重新打开文件,然后用修改后的数据覆盖原始文件;或 (2) 您用修改后的数据写出一个新文件。

    【讨论】:

    • 注意:可以在同一行打开两个文件
    • @cricket_007 我知道,但这会使代码复杂化,并且 OP 是初学者。教初学者一次使用with 一个文件更容易。
    【解决方案2】:

    为什么你甚至需要一个文件并不完全清楚

    如果您的字面意思是“删除字符串中的第一个字符”并且不是文件的每一行,那么只需剥离消息字符串

     x = 10 # some number 
    msg = clientsocket.recv(1024)
    if len(msg) < 2:
      print "Exit"
      break
    msg = msg.replace('\n','').replace(' ','')[x:] 
    print(msg)
    

    如果您确实想将字符串写入文件,那么您只需在编辑消息后打开一次即可

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多