[英]How to get first letter of each line in python?
here is what I got txt and open txt file looks like这是我得到的 txt 和打开的 txt 文件看起来像
f = open('data.txt', 'r')
print(f.read())
the show['Cat\n','Dog\n','Cat\n','Dog\n'........]节目['Cat\n','Dog\n','Cat\n','Dog\n'........]
output But I would like to get this output但我想得到这个
['C\n','D\n','C\n','D\n'........]
['C\n','D\n','C\n','D\n'.......]
First you'll want to open the file in read mode ( r
flag in open
), then you can iterate through the file object with a for loop to read each line one at a time.首先,您需要以读取模式打开文件(
r
标志为open
),然后您可以使用 for 循环遍历文件 object 以一次读取每一行。 Lastly, you want to access the first element of each line at index 0 to get the first letter.最后,您要访问索引 0 处每行的第一个元素以获取第一个字母。
first_letters = []
with open('data.txt', 'r') as f:
for line in f:
first_letters.append(line[0])
print(first_letters)
If you want to have the newline character still present in the string you can modify line 5 from above to:如果您想让换行符仍然出现在字符串中,您可以将第 5 行从上面修改为:
first_letters.append(line[0] + '\n')
f = open("data.txt", "r")
for x in f:
print(x[0])
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.