如何读取Python中字符串的每一行并将选择的行存储为数组中的元素?
我想逐行读取文件,每行都附加到数组的末尾。我无法在任何地方找到如何做到这一点,我找不到如何在Python中创建一个字符串数组。
例如:
线路1 =
abc def gef
lmn qrt was
lmh kjd lxm
skd fdj djk
ndz weg tdg
ndg has dbg
pef rah vdg
pas dgh ghr
bde ghx ore
我的输出应该是:
line1[0]= abc def gef
lmn qrt was
lmh kjd lxm
line1[1]= skd fdj djk
ndz weg tdg
ndg has dbg
line1[2]= pef rah vdg
pas dgh ghr
bde ghx ore
答案 0 :(得分:3)
>>> line1 = """abc def gef
... lmn qrt was
... lmh kjd lxm
...
... skd fdj djk
... ndz weg tdg
... ndg has dbg
...
... pef rah vdg
... pas dgh ghr
... bde ghx ore"""
>>> line1.split("\n\n")
['abc def gef\nlmn qrt was\nlmh kjd lxm',
'skd fdj djk\nndz weg tdg\nndg has dbg',
'pef rah vdg\npas dgh ghr\nbde ghx ore']
>>> for number, item in enumerate(line1.split("\n\n")):
... print("Line number {0}".format(number))
... print(item)
...
Line number 0
abc def gef
lmn qrt was
lmh kjd lxm
Line number 1
skd fdj djk
ndz weg tdg
ndg has dbg
Line number 2
pef rah vdg
pas dgh ghr
bde ghx ore
>>>
答案 1 :(得分:0)
这样的事情:
line1="""abc def gef
lmn qrt was
lmh kjd lxm
skd fdj djk
ndz weg tdg
ndg has dbg
pef rah vdg
pas dgh ghr
bde ghx ore"""
lis = [""]
for line in line1.splitlines():
if line.strip():
lis[-1] += "\n"+ line
else:
if lis[-1] != "":
lis.append("")
print lis[0]
print lis[1]
print lis[2]
<强>输出:强>
abc def gef
lmn qrt was
lmh kjd lxm
skd fdj djk
ndz weg tdg
ndg has dbg
pef rah vdg
pas dgh ghr
bde ghx ore
答案 2 :(得分:0)
这将打开一个文件,并将所有行读入名为lines
的变量中。它还会为您删除尾随的新行。
with open('<<FILENAME>>', 'r') as file:
lines = [line.rstrip() for line in file.readlines()]
解剖:
with open...
表示您正在为'r'
读取打开FILENAME,并命名生成的文件对象file
。在它下面的块完成后它将被销毁。
lines =
将右侧的表达式指定给lines
[line.rstrip() for line in file.readlines()]
从文件内容中创建列表:
line.rstrip()
发生在file.readlines()
结果中的每一行,它会删除尾随的新行。for line in
是枚举某些内容结果的方法(参见Python List Comprehensions)。file.readlines()
返回所有行(及其行尾)按新行分割的列表。