我将如何重写文件,以便它变得更易于管理



问题是我正在尝试编写代码,以便将我的.txt文件重写为更易于管理的版本。"程序"需要一次读取七行,然后将其写出为另一个.txt文件中的单行,然后重复此功能,直到它遍历整个.txt文件。

我一直在互联网上寻找并尝试了多种方法,但是没有一件甚至接近我需要的最接近的是以下代码。

first_line = 7
def function():
    with open ('file_txt', 'r') as read_file1:
            line = [next(read_file1) for x in range(first_line)]
            with open ('file_txt_new', 'w') as write_file2:
                    write_file2.write(str(line))

输入文本文件如下所示:

Awakened Shrub
Small plant, unaligned
Hit Points:
10 (3d6) Armor Class:
9 Speed:
20 ft. Challenge Rating:
0 (10 XP)

预期结果:这些结果只是在一行中重写的原始文本文件。

示例 1:这将写在新文本文档的第一行上。

Awakened Shrub, Small plant, unaligned, Hit Points: 10 (3d6) Armour Class: 9

示例 2:这将写在新文本文档的第二行。

Baboon, Small beast, unaligned, Hit Points: 1 (1d4 - 1) Armour Class: 9

实际结果:

['Awakened Shrubn', 'Small plant, unalignedn', 'baboonn', 'Small beast, unalignedn',]

你的代码正在制作list s,但要做你想做的事情,你需要把它们重新组合成一个字符串(str(line)不这样做,因为这只会产生list的字符串表示;你需要str.join

):
first_line = 7
def function():
    # Open output file once up front (or you'll replace it for each new set of seven lines)
    with open('file_txt', 'r') as read_file1, open('file_txt_new', 'w') as write_file2:
        while True:
            # Get the lines, providing a default value to next in case you run out of lines
            lines = [next(read_file1, '') for x in range(first_line)]
            # Convert to a single string, and replace newlines with `, ` matching expected output
            newline = ''.join(lines).rstrip('n').replace('n', ', ')
            # Got nothing but empty lines, must have exhausted file, so we're done
            if not newline:
                break
            write_file2.write(newline + "n")

注意:您可以使用 itertools.islice 稍微简化/加快代码,假设您可以导入模块,替换:

            lines = [next(read_file1, '') for x in range(first_line)]

跟:

            lines = itertools.islice(read_file1, first_line)
我认为

以下代码对您有所帮助:

num_reads = 7
with open('data.txt') as read_file:
    with open('new_data.txt', 'w') as write_file:
        while (True):
            lines = []
            try:       # You should expect errors if the number of lines in the file are not a multiplication of num_reads
                for i in range(num_reads):     
                    lines.append(next(read_file))  # when the file finishes an exception occurs here
                #do sutff with the lines (exactly num_reads number of lines)
                processed = " ".join(list(map(lambda x: x.replace("n", ''), lines)))
                write_file.write(processed + 'n')
            except StopIteration:     # here we process the (possibly) insufficent last lines
                #do stuff with the lines (less that  num_reads)
                processed = " ".join(list(map(lambda x: x.replace("n", ''), lines)))
                write_file.write(processed + 'n')
                break

当到达文件末尾时,except会引发并捕获StopIteration错误,您可以在其中处理可能捕获的数据行不足并中断while循环。在上面的代码段中,我对完整 (num_reads = 7) 捕获和部分捕获都执行了相同的操作。处理部分仅附加行并删除换行符。当data.txt是这样的:

line1
line2
line3
line4
line5
line6
line7
line8
line9
line10

new_data.txt会是这样的:

line1 line2 line3 line4 line5 line6 line7
line8 line9 line10

最新更新