[英]Read a file line by line but only some characters within each line
I have a text file and I would like to get the string from the 300th character to the 500th character (or column in the text file) within each line and put the string into a list. 我有一个文本文件,我想将字符串从第300个字符转换为第500个字符(或文本文件中的列),并将其放入列表中。
I started my code with this but I don't know how to modify the file reading with specifying the ch. 我以此开始代码,但是我不知道如何通过指定ch来修改文件读取。
with open("filename") as f:
for line in f:
for ch in line:
Try: 尝试:
with open("filename") as f:
for line in f:
chs = line[299:500]
This should slice it and return the characters from 300-500. 这应该切成薄片并返回300-500之间的字符。 From there, you could just do list.append
to put it into a list, or whatever you need to do. 从那里,您可以只执行list.append
将其放入列表中,或执行任何其他操作。
You can use the subscript slicing notation on python strings: 您可以在python字符串上使用下标切片符号:
lines = []
with open("filename") as f:
for line in f:
lines.append(line[300:500])
Or 要么
with open("filename") as f:
lines = [l[300:500] for l in f]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.