我目前正在开发一个应用程序,该应用程序需要从文件中读取所有输入,直到遇到某个字符。
通过使用代码:
file=open("Questions.txt",'r')
c=file.readlines()
c=[x.strip() for x in c]
每次脱衣相遇\n
,它从输入中删除并被视为列表中的字符串c
.
这意味着每一行都被分成列表的一部分c
. But 我想在遇到特殊字符时列出一个列表像这样:
如果输入文件包含以下内容:
1.Hai
2.Bye\-1
3.Hello
4.OAPd\-1
然后我想得到一个列表c=['1.Hai\n2.Bye','3.Hello\n4.OApd']
请帮我做这件事。
最简单的方法是将文件作为单个字符串读取,然后将其拆分为分隔符:
with open('myFileName') as myFile:
text = myFile.read()
result = text.split(separator) # use your \-1 (whatever that means) here
如果您的文件非常大,请将完整内容作为单个字符串保存在内存中以供使用.split()
可能是不可取的(然后在拆分后将完整内容保留在列表中可能也是不可取的)。然后你可以分块阅读:
def each_chunk(stream, separator):
buffer = ''
while True: # until EOF
chunk = stream.read(CHUNK_SIZE) # I propose 4096 or so
if not chunk: # EOF?
yield buffer
break
buffer += chunk
while True: # until no separator is found
try:
part, buffer = buffer.split(separator, 1)
except ValueError:
break
else:
yield part
with open('myFileName') as myFile:
for chunk in each_chunk(myFile, separator='\\-1\n'):
print(chunk) # not holding in memory, but printing chunk by chunk
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)