You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python文本列表元素逐行输出与脚本结果格式调整需求

Solution for Your Python File Handling Tasks

Let's break down how to solve both of your requirements clearly:

1. Read a TXT File's List and Write Each Value to a New File Line by Line

If you need to take the contents of a source TXT file (where values might be space-separated or line-separated) and write each individual value on its own line in a new file, here's a straightforward function:

def write_values_line_by_line(input_path, output_path):
    with open(input_path, "r") as infile, open(output_path, "w") as outfile:
        for line in infile:
            # Split each line into values (handles space-separated entries)
            values = line.strip().split()
            for val in values:
                outfile.write(f"{val}\n")

How to use it:

write_values_line_by_line("your-input-file.txt", "new-output.txt")

This function reads the input file line by line, splits each line into individual values (ignoring any leading/trailing whitespace), then writes each value to the output file on a separate line.


2. Modify Your Existing Diff Script to Write Values One Per Line

Looking at your current code, the Diff function is writing the result as a stringified list (like ['val1', 'val2']), which isn't what you want. Let's fix that by adjusting how we write the results to the file:

Modified Full Code:

def readIntoList(path):
    with open(path, "r") as text1:
        lines = text1.readlines()
        result = []
        for l in lines:
            l_list = l.replace("\n", "").split(" ")
            result.extend(l_list)
    return result

def Diff(li1, li2):
    # Calculate the difference between the two sets
    diff_values = set(li2) - set(li1)
    with open("final-output.txt", "w") as f:
        # Write each value on a separate line
        for val in diff_values:
            f.write(f"{val}\n")
        # Alternatively, use this concise line for the same result:
        # f.write('\n'.join(diff_values))

if __name__ == '__main__':
    a = readIntoList('file2.txt')
    b = readIntoList('file3.txt')
    Diff(a, b)

Key Changes Made:

  • Instead of converting the set difference to a string with str(list(...)), we directly iterate over the diff_values set.
  • For each value in the difference set, we write it to the file followed by a newline character (\n), ensuring each value gets its own line.
  • We also kept the file handling within a with statement (your original code didn't explicitly close the file—using with ensures proper automatic closure).

This will produce an output file where each numeric value from the difference is on its own line, no square brackets or quotes.

内容的提问来源于stack exchange,提问作者london2012_dd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:17:49