跳过 txt 文件中的行,然后开始读取数据

Skipping lines in a txt file and start reading the data after that

提问人:asw107 提问时间:6/27/2023 最后编辑:anoasw107 更新时间:6/28/2023 访问量:43

问:

我正在尝试跳过 txt 文件的前 23 行并从第 24 行开始读取数据。在文件类型更改之前,脚本本身运行良好,现在我需要跳过前 23 行文本。

我尝试了两种方法:

with open("D:\\Annette testing from 19 May onwards\\30cm", "*.txt",'r') as f:
    lines_after_23 = f.readlines()[23:]
    
with open("D:\\Annette testing from 19 May onwards\\30cm", "*.txt") as f:
    for line in itertools.islice(f, 24, None):  
       

但我无法让它工作......我做错了什么?

原始脚本(我需要在此脚本中添加跳过行):

import os
import glob
from NAP_transform import transform

# %% importing and transforming all files

file_path = os.path.join("D:\\Annette testing from 19 May onwards\\30cm", "*.txt")
filenames = glob.glob(file_path)

# %% TRANSFORMING 0 DEGREE MEP NO NECK IMPACTS

# Processing each impact in the folder

for a in filenames:
     print("Now processing:", a)
# Set the name for the impact
# impact_name = a.replace("D:\\Annette testing from 19 May onwards\\", "")
# impact_name = impact_name.replace("\\", " ") # Replace slash with spaces
    impact_name = a.replace("txt", "csv") # Set as a csv file

# Transforming the data
    data_out =  transform(a, 2021)

# Setting the file path for the export files
# export_file_path = "D:\\Annette testing from 19 May onwards\\" + impact_name

# Creating and saving the full data file
    data_out.to_csv(impact_name)
python txt 跳过

评论


答:

0赞 Mark 6/27/2023 #1
# test.txt is just the numbers 1-30, one per line
with open('test.txt', 'r') as f:
    # start reading from the 24th line
    for line in f.readlines()[23:]:
        print(line, end='')

# 24
# 25
# 26
etc.

问题是 part- open 采用以下参数:with open("D:\Annette testing from 19 May onwards\30cm", "*.txt",'r') as f: lines_after_23 = f.readlines()[23:]"D:\Annette testing from 19 May onwards\30cm", "*.txt",'r'

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

但是您已经传递了两个文件名(我假设您试图读取“30cm”文件夹中的每个文本文件?

在这种情况下,您想要的是:

import os

for file in os.listdir("D:\Annette testing from 19 May onwards\30cm"):
    if file.endswith(".txt"):
        with open(file, 'r') as f:
            for line in f.readlines()[23:]:
                # do something with the line
                print(line, end='')