简体   繁体   中英

Python: How do I use this code snippet to append text to the next line?

I have made a python based quiz game. One of my functions reads text from a file and imports it as a dictionary to use as the question/answer base. I have a file called nmapQuestions.txt and portQuestions.txt. I intend to continually add pages of questions. I'm using the below code snippet to make one text file in my directory have ALL the questions in one document. A master quiz if you will. I have one issue. When this appends 2 files together the second file doesnt start on a new line it starts at the end of the line of the last file how do I get this to append to a new line?

def master_list():
    outfilename = "zMasterList.txt"

    with open(outfilename, 'wb') as outfile:
        for filename in glob.glob('*.txt'):
            if filename == outfilename:
                continue
            with open(filename, 'rb') as readfile:
                shutil.copyfileobj(readfile, outfile)

OUTPUT:

What is port -T4?: ,intensity

What is port -sS?: ,syn scan

What is port -sA?: ,ack scan

What is port -p?: ,port scan

What is port -sT?: ,tcp scan

What is port -sW?: ,windows scan

What is port -sM?: ,maimon scan

What is port -iL?: ,scan from file

What is port -iR?: ,random scan

What is port -sU?: ,udp scanWhat is port 15?: ,netstat <--- 2 on the same line

What is port 20?: ,ftp data

What is port 21?: ,ftp command

What is port 22?: ,ssh

What is port 23?: ,telnet remote login

What is port 25?: ,smtp

What is port 53?: ,dns

What is port 80?: ,http

What is port 110?: ,post office protocol

What is port 111?: ,rcp bind

Help is definitely appreciated please and thank you

Seems like you should make sure your file ends with a newline character.

One solution would be to append the newline first, and then copy the rest of the file.

So you'd only need to add:

print(file=outfile)

which will add a new line to your outfile .

If you want to add 2 lines, do instead:

print("\n", file=outfile)

After doing some research I found you could add a new line to the end of the block with the following code:

outfile.write(b"\\n")

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