简体   繁体   中英

Python: Modifying text file after certain character

I'm doing some operations on a text file with python. But there is one thing I couldn't find a solution yet. I hope someone here can help me.

In that text file in every line I have the word order and afterwards a various string consisting of , and numbers.

Now I want to delete the word order and everything that follows in that line, but I can't find out how. The location in the file where order is stated always varies, so I cannot point to a certain location and delete everything afterwards.

It's extremly easy to do what you want because you only DELETE parts of the text, so you can rewrite in the same file that you read by using the 'r+' mode.

with open(filename,'r+') as fr,open(filename,'r+') as fw:
    for line in fr:
        x = line.find('order')
        fw.write(line if x==-1
                 else line[0:x]+'\n' if '\n' in line
                 else line[0:x])
    fw.truncate()

If your file isn't too big, so can be entirely read and hold in the RAM, here's another method using a regex:

import re

r = re.compile('(.*?)(?:order.*?$|\Z)',
               re.MULTILINE|re.DOTALL)

with open(filename,'r+') as f:
    x = f.read()
    f.seek(0,0)
    f.write(''.join(r.findall(x)))
    f.truncate() 

iterate over the file line by line (I assume you are already doing this) then use string.find :

>>> import string
>>> x = 'helloORDERme'  
>>> string.find(x,"ORDER")
5
>>> x[:string.find(x,"ORDER")]
'hello'

or if you really need to know that as well:

import string
with open('myfile', 'rU') as f:
  for line in f:
     print line[:string.find(line,"order")]

I'll leave writing the updated values back out as an excercise for the asker.

lines = "hello1OrderABC\nhello2OrderDEF".splitlines()
for line in lines:
  print line[:line.find("Order")]
------
hello1
hello2

First line creates a list of lines ['hello1OrderABC', 'hello2OrderDEF']. The rest iterates through this list and prints out everything upto the word "Order".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM