Python文本列表元素逐行输出与脚本结果格式调整需求
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 thediff_valuesset. - 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
withstatement (your original code didn't explicitly close the file—usingwithensures 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

