[英]Python reading file and get a substring
I read a file which contains: 我读了一个文件,其中包含:
> hello world
Using the following code to read this file, but I can't read a part of it 使用以下代码读取此文件,但无法读取其中的一部分
with open("/home/pi/example1.txt") as f1:
test = f1.readlines(0)
print (test)
print (test[0:2])
expected output: 预期输出:
Hello world
He
Output what I get 输出我得到的
['helloworld\r\n']
['helloworld\r\n']
What is the right (and SIMPLE) way to get a part of a substring what I grab from a file? 从文件中获取子字符串的一部分的正确(简便)方法是什么?
readlines()
returns a list, as you can see in your output the string is actually part of a one-item list: readlines()
返回一个列表,正如您在输出中看到的那样,字符串实际上是一个单项列表的一部分:
>>> f = ['helloworld\r\n']
>>> f[0][0:2]
'he'
To fix your original code, you need to move the 0 after the readlines call: 要修复原始代码,您需要在readlines调用后将 0移到:
test = f1.readlines()[0]
However, as you are using the with
statement, your life is a lot simpler: 但是,当您使用
with
语句时,您的生活要简单得多:
with open("/home/pi/example1.txt") as f1:
for line in f1:
print(line)
print(line[0:2])
Just change a bit to : 只需更改为:
with open("/home/pi/example1.txt") as f1:
for test in f1:
print(test)
print(test[0:2])
Other way readline returns a list then just use the indexing line readline()[0] readline以其他方式返回列表,然后仅使用索引行readline()[0]
Here is the correct code that you want. 这是您想要的正确代码。
with open("/home/pi/example1.txt") as f1:
test = f1.readlines(0)
print (test[0])
print (test[0][0:2])
But alternatively you can use the following approach. 但是,您也可以使用以下方法。
with open("/home/pi/example1.txt") as f1:
test = f1.readline()
print (test)
print (test[0:2])
You can use the .strip() function which is available to remove all the white space and new line characters from a string 您可以使用.strip()函数,该函数可从字符串中删除所有空白和换行符
with open('../../xx.txt','r') as fi:
for line in fi:
print(line.strip())
print(line[0:2])
I didn't used the .strip() method in the second print statement because we are just getting the initial part of a string . 我没有在第二个print语句中使用.strip()方法,因为我们只是获取string的初始部分。 so it will not be a new line character(let's hope so).
因此它不是换行符(希望如此)。 In case if you want you can use for that line also
如果您愿意,也可以用于该行
print(line[0:2].strip())
strip() method will be really helpful specially if you are using the string later for any comparison. 如果您以后使用字符串进行任何比较,则strip()方法将特别有用。
the readlines return a list 阅读线返回列表
use test[0] for substring 使用test [0]作为子字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.