python - 如何从文本文件中获取一些值到列表中然后写入?
问题描述
我正在设置一个脚本,我需要从一个文本文件中获取一些值到一个列表中。这是我的文本文件的体系结构:
someValue
someValue
someValue
Value
example1
example2
Value
example3
example4
someValue
someValue
Value
example5
[...]
预期的输出是:
my_list = [['Value', 'example1', 'example2', '\n'], ['Value', 'example3', 'example4', '\n'], ['example5', ..]]
但我得到这个:
my_list = [['Value', 'example1', 'example2'], ['Value', 'example1', 'example2'], ['Value', 'example1', ..]]
当我试图把它写在一个文件上时,我写了这个:
[example1, example2]
在我的档案上。
但我想获得这个(使用'\n'):
example1
example2
我试过这个:
f = open(file, 'r')
for num, lines in enumerate(f, 1):
my_list.append(lines)
if 'Value' in lines:
my_list_2.append(num)
for i in range(len(my_list_2)):
number_of_lines = my_list_2[i+1] - my_list_2[i]
for j in range(int(number_of_lines)):
extract.append(my_list[my_list_2[0]+j])
file = open(file2, 'w')
for k in range(len(extract)):
file.write(extract[k])
各种帮助表示赞赏。提前致谢。
解决方案
考虑一种在第一次读取时捕获相关行的方法。我们可以设置一个布尔值,让循环知道我们是否应该在遇到时添加行Value
:
f = open(file, 'r')
lines = f.readlines()
# what we'll be writing to a file
output = list()
# the current captured lines to be added to output
current = list()
# boolean specifying whether we should be trying to add lines to current
found = False
for line in lines:
# stop adding lines to current when we encounter a line without a space as its first character
if found and not line.startswith(' '):
found = False
output.append(list(current))
current = list()
# add lines to our current list if our boolean is set, otherwise be looking for 'Value'
if found:
current.append(line[1:])
elif line == 'Value\n':
found = True
current.append(line)
# make sure to add values if current isn't empty after the loop's execution
if current:
output.append(current)
这给了我们我们的output
:
output = [['Value\n', 'example1\n', 'example2\n'], ['Value\n', 'example3\n', 'example4\n'], ['Value\n', 'example5\n']]
然后我们可以轻松地将其写入文件(确保使用附加选项打开a
):
with open(file2, 'a') as wf:
for x in output:
for val in x[1:]:
wf.write(val)
输出文件的内容将是:
example1
example2
example3
example4
example5
包括尾随换行符。希望这可以帮助!
推荐阅读
- git - 为什么git要删除文件?
- javascript - 意外的对象更改
- javascript - 重写函数以通过数组中的匹配 id 查找对象,更新值并设置反应状态
- maven - maven:定义和使用不同的构建场景
- sql-server - 为什么这个存储过程在执行时会尝试将 nvarchar 转换为 int
- webrtc - 使用 navigator.getUserMedia 时未定义流
- javascript - 是否可以使用greasemonkey/tampermonkey 将GM_xmlhttpRequest 用于我的数据表单?
- python - Python 和 ezdxf 复制块
- paypal - 这真的是您进行一次性付款的方式吗?
- java - 从 Java 程序运行 Docker 运行命令