相关文章推荐
曾经爱过的猴子  ·  org.apache.poi.EmptyFi ...·  2 月前    · 
曾经爱过的猴子  ·  类变量和实例变量·  7 月前    · 
曾经爱过的猴子  ·  Popover | Element Plus·  9 月前    · 
曾经爱过的猴子  ·  Pandas DataFrame: ...·  9 月前    · 
私奔的领结  ·  Android ...·  12 小时前    · 
暗恋学妹的投影仪  ·  Android ...·  12 小时前    · 
精明的茶叶  ·  拦截tablayout ...·  12 小时前    · 
傻傻的凳子  ·  TabLayout ...·  12 小时前    · 
温柔的野马  ·  XMLHttpRequest.withCre ...·  13 小时前    · 

使用 with open() 读取文件,使用 next(file) 可以跳过一行

def get_data_from_file(file_path, skip_line: int = 0):
    """从文件得到数据源"""
    # skip 为跳过的行数
    with open(file_path, 'r') as file:
        for i in range(skip_line):
            next(file)  # 跳过一行
        while True:
            line = file.readline()
            if not line:
                break  # 退出
            yield line
if __name__ == '__main__':
    for i in get_data_from_file("test.txt", skip_line=2):
        print(i)

其中test.txt文件内容如下:

hello1
world1
hello2
world2
hello3
world3
hello4
world4
hello5
world5
hello6
world6
hello7
world7
hello8
world8
hello9
world9
                    使用with open()读取文件,使用next(file)可以跳过一行示例代码def get_data_from_file(file_path, skip_line: int = 0):    """从文件得到数据源"""    # skip 为跳过的行数    with open(file_path, 'r') as file:        for i in range(skip_line):            next(file)  # 跳过一行        while Tru
				
Python编程时,经常需要跳过第一读取文件内容。比较容易想到是为每设置一个line_num,然后判断line_num是否为1,如果不等于1,则进读取操作。相应的Python代码如下: input_file = open("C:\\Python34\\test.csv") line_num = 0 for line in islice(input_file, 1, None): linecache.getline('./data.txt', 5) 读取文件的第5,实际该文件会整个缓存起来,可以使用linecache.cache这个dict成员查看所有缓存的内容。所以大文件读取不适合这种方法。 方法二:使用linecache
文章目录csv 获取到想要的行数,跳过若干xlsx 获取到想要的行数,跳过若干 csv 获取到想要的行数,跳过若干 file_name = 'xxx.xls' title_list = '证券代码' with open(file_name, 'r') as f: reader = csv.reader(f) for row_num, row in enumerate(reader): row_list = row[0].split('\t') if ti
 
推荐文章