简体   繁体   中英

How to write new line to a file in Python?

I have a function where conversion is a list and filename is the name of the input file. I want to write 5 characters in a line then add a new line and add 5 characters to that line and add a new line until there is nothing to write from the list conversion to the file filename. How can I do that?

Convert the list of strings into one large string, then loop through that string five characters at a time and insert "\\n" after each iteration of the loop. Then write that to a file. Here's a basic example of what I mean, might need some tweaking but it'll give you the idea:

# concatenate all the strings for simplicity
big_string = ""
for single_string in conversion:
    big_string += single_string

# loop through using 5 characters at a time
string_with_newlines = ""
done = False
while not done:
    next_five_chars = big_string[:5]
    big_string = big_string[5:]
    if next_five_chars:
        string_with_newlines += next_five_chars + "\n"
    else:
        done = True

# write it all to file
with open(filename, "w") as your_file:
    your_file.write(string_with_newlines)

From what I think I understand about your question, you may need code that looks like this:

import os
def write_data_file(your_collection, data_file_path):
    """Writes data file from memory to previously specified path."""
    the_string = ''
    for row in your_collection:
        for i, c in enumerate(row):
            if i % 5 < 4:
                the_string += c
            else:
                the_string += os.linesep + c
    with open(data_file_path, 'w') as df:
        df.write(the_string)

my_collection = [
    "This is more than five characters",
    "This is definately more than five characters",
    "NOT",
    "NADA"
]
write_data_file(my_collection, '/your/file/path.txt')

Other than that, you may need to clarify what you are asking. This code snippet loops through a collection (like a list) then loops over the assumed string contained at that row in the collection. It adds the new line whenever the 5 character limit has been reached.

def foo(conversion, filename):
    with open(filename, "a") as f:
        line = ""
        for s in conversion:
            for c in s:
                if len(line) < 5:
                    line += c
                else:
                    f.write(line + "\n")
                    line = c
        f.write(line)

I made a function for grouping your list:

import itertools
def group(iterable, n):
    gen = (char for substr in iterable for char in substr)
    while True:
        part = ''.join(itertools.islice(gen, 0, n))
        if not part:
            break
        yield part

Presentation:

>>> l = ['DBTsiQoECGPPo', 'd', 'aDAuehlM', 'FbUnSuMLuEbHe', 'jRvARVZMn', 'SbGCi'
, 'jhI', 'Rpbd', 'uspffRvPiAmbQEoZDFAG', 'RIbHAcbREdqpMDX', 'bqVMrN', 'FtU', 'nu
fWcfjfmAaUtYtwNUBc', 'oZvk', 'EaytqdRkICuxqbPaPulCZlD', 'dVrZdidLeakPT', 'qttRfH
eJJMOlJRMKBM', 'SAiBrdPblHtRGpjpZKuFLGza', 'RxrLgclVavoCmPkhR', 'YuulTYaNTLghUkK
riOicMuUD']
>>> list(group(l, 5))
['DBTsi', 'QoECG', 'PPoda', 'DAueh', 'lMFbU', 'nSuML', 'uEbHe', 'jRvAR', 'VZMnS'
, 'bGCij', 'hIRpb', 'duspf', 'fRvPi', 'AmbQE', 'oZDFA', 'GRIbH', 'AcbRE', 'dqpMD
', 'XbqVM', 'rNFtU', 'nufWc', 'fjfmA', 'aUtYt', 'wNUBc', 'oZvkE', 'aytqd', 'RkIC
u', 'xqbPa', 'PulCZ', 'lDdVr', 'ZdidL', 'eakPT', 'qttRf', 'HeJJM', 'OlJRM', 'KBM
SA', 'iBrdP', 'blHtR', 'GpjpZ', 'KuFLG', 'zaRxr', 'LgclV', 'avoCm', 'PkhRY', 'uu
lTY', 'aNTLg', 'hUkKr', 'iOicM', 'uUD']
>>> '\n'.join(group(l, 5))
'DBTsi\nQoECG\nPPoda\nDAueh\nlMFbU\nnSuML\nuEbHe\njRvAR\nVZMnS\nbGCij\nhIRpb\ndu
spf\nfRvPi\nAmbQE\noZDFA\nGRIbH\nAcbRE\ndqpMD\nXbqVM\nrNFtU\nnufWc\nfjfmA\naUtYt
\nwNUBc\noZvkE\naytqd\nRkICu\nxqbPa\nPulCZ\nlDdVr\nZdidL\neakPT\nqttRf\nHeJJM\nO
lJRM\nKBMSA\niBrdP\nblHtR\nGpjpZ\nKuFLG\nzaRxr\nLgclV\navoCm\nPkhRY\nuulTY\naNTL
g\nhUkKr\niOicM\nuUD'

Write the result of '\\n'.join(group(l, 5)) to a file.

l = ["one", "two", "three", "four", "five"]


def write(conversion, filename):
    string = "".join(conversion)
    f = open(filename, "a")
    for i in range(5, len(string) + 5, 5):
        f.write(string[i-5:i])
        f.write("\n")

if __name__ == '__main__':
    write(l, "test.txt")

This create a file called "test.txt" with the content:

onetw
othre
efour
onetw
othre
efour
five

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