簡體   English   中英

如何在Python中將新行寫入文件?

[英]How to write new line to a file in Python?

我有一個函數,其中轉換是一個列表,文件名是輸入文件的名稱。 我想在一行中寫入5個字符,然后添加新行,並在該行中添加5個字符,然后添加新行,直到沒有任何內容可以從列表轉換寫入文件名。 我怎樣才能做到這一點?

將字符串列表轉換為一個大字符串,然后一次遍歷該字符串五個字符,並在每次循環迭代后插入“ \\ n”。 然后將其寫入文件。 這是我的意思的基本示例,可能需要進行一些調整,但是它可以為您提供想法:

# 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)

根據我對您的問題的理解,您可能需要如下代碼:

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')

除此之外,您可能需要澄清您的要求。 此代碼段循環遍歷一個集合(如列表),然后循環遍歷該集合中該行包含的假定字符串。 每當達到5個字符的限制時,它將添加新行。

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)

我為分組列表做了一個功能:

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

介紹:

>>> 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'

'\\n'.join(group(l, 5))的結果寫入文件。

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")

這將創建一個名為“ test.txt”的文件,其內容為:

onetw
othre
efour
onetw
othre
efour
five

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM