[英]How can I grab some values from a text file into a list then write it?
我正在设置一个脚本,我需要从文本文件中获取一些值到列表中。 这是我的文本文件的体系结构:
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
包括结尾的换行符。 希望这可以帮助!
我将尝试解释如何解决此问题:
for num, lines in enumerate(f, 1):
my_list.append(lines)
newlist = []
for i in range(len(my_list)):
splitlist = my_list[i].splitlines()
for j in range(len(splitlist)):
newlist.append(splitlist[j])
通过这样做,我获得了一个列表,其中元素是文件中的所有行。
然后,我创建了一些列表,其中包含我的特定字符串的幻影索引:
index = []
for i in range(len(newlist)):
if newlist[i].startswith('string1'):
index.append(i+1)
我遇到了添加\\n
的问题,因为当我在新文本文件中写入列表中的所有项目时,我才进行管理。
希望我已经解释清楚了。 如有任何疑问,请发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.