简体   繁体   中英

How do I find all strings of length 7 in a text file and then save those strings to a new text file in Python?

I have a file of all the words in a Scrabble dictionary. I am very new to coding but I want to create a new file where it takes all the 7 letter words and copies them into a new file. How do I do that?

Assuming your input file has one word per line, you can read each line, check the length of the word and if it is 7, write to the output file:

with open('input.txt', 'r') as f_in, open('output.txt', 'w') as f_out:
    for line in f_in:
        if len(line.strip()) == 7: # we strip the newline and possible spaces
            f_out.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