简体   繁体   中英

Writing Specific lines of a text file into a text file - Python

I am new Python. I have a simple task of writing specific lines of a text file to another text file. The format of the text file is like

.A
some text1 -- skip
some text2 -- skip
.B
.some text3 -- write
.some text4 -- write

I need to skip data between .A and .B and when I encounter .B start writing data from some text3..etc to the new file.

I am using Python 2.7

I tried this -

with open("Myfile.txt","r") as myfile:
     for line in myfile:
        if line.startswith(".A"):  
            writefile = open("writefile.txt", "a")
        else:
            if not (line.startswith(".B")):
                continue
            else:
                writefile.write(line)

I think in else block I messed up the things..

A simple approach would be something like this :

fname = 'D:/File.txt'
content = []
with open(fname) as f:
    content = f.readlines()
wflag= True
f = open('D:/myfile.txt','w')
for line in content:
    if(line=='.A\n'):
        wflag = False
    if(line=='.B\n'):
        wflag= True
        continue
    if(wflag):
        f.write(line) # python will convert \n to os.linesep
f.close()

Their is lot more pythonic ways to do it using some regular expression, but as you said you are a beginner , so i am posting a simple programmers approach.

The question is not exactly clear but perhaps you want something like this,

skip_line = True
writefile = open("writefile.txt", "a")
with open("Myfile.txt","r") as myfile:
     for line in myfile:
        if line.startswith(".A"):
            skip_line = True
        elif line.startswith(".B"):
            skip_line = False
        else:
            pass
        if skip_line:
            continue
        writefile.write(line)

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