简体   繁体   English

逐行读取文件,但每行中仅读取一些字符

[英]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.

相关问题 如何逐行读取文件并在python的每一行中获取一些字符串 - How to read a file line by line and get a some string in each line in python 读入文件并仅打印每行的最后一个单词(如果这些单词为8个字符或更长,并且不包含#,@或:符号) - Read in file and print only the last words of each line if these words are 8 characters or longer and dont contain #, @ or : symbols 在每行的开头添加一些字符 - Add some characters at the beginning of each line 逐行读取文件,并获得以某个单词开头的行? - Read a file line by line,and get the line that starts with some word? python:在每一行读取一个文件,仅将int存储到列表中 - python: read a file on each line and store only ints into list 只读文件的第一行? - Read only the first line of a file? 读取文本文件的每一行,然后在python中用空格分隔每一行 - Read each line of a text file and then split each line by spaces in python Python - 读取文本文件的每一行并将每一行传递给变量 - Python - Read each line of text file and pass each line to variable 使用python将字符追加到txt文件中的每一行 - Appending characters to each line in a txt file with python 在Python中读取带有行继续符的文件 - Read a file with line continuation characters in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM