无法从.csv文件的特定行提取数据

igsr9ssn  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(84)

我正在编写一个python程序,它遍历文件夹中的所有.csv文件,并从每个文件中复制第二条规则。当我尝试从.csv文件的第二行提取数据时,由于某种原因无法工作。
我试图立即从.csv文件中读取它,但没有成功。之后,我尝试先将所有内容写入.txt文件,然后读取它。这也不起作用。
这是我现在的代码:

import os
import re
import csv
import pandas as pd
from tkinter import filedialog
from itertools import islice
from io import StringIO

#select folder + file
root = filedialog.Tk()
root.withdraw()

#folder which contains all the .csv files
target_folder = filedialog.askdirectory()

#file where necessary content from .csv files gets wrote to
target_file = filedialog.askopenfilename()

#Loop through all files in target folder and grab .csv files
content = []

for subdir, dirs, files in os.walk(target_folder):
    for filename in files:
        filepath = subdir + os.sep + filename
        
        if filename.lower().startswith('autopilot'):
            with open(os.path.join(subdir, filename)) as f:
                data = f.read()
                print(data)

字符串
它现在输出所有数据,但我希望它只输出每个.csv文件的第2行。

0vvn1miw

0vvn1miw1#

您读取并打印所有文件^

print(data)

字符串
改为

data = f.readlines()
print(data[1])  # print second line


阅读更多在此answer

mfpqipee

mfpqipee2#

您需要从所选文件中读取行,然后在打印第二行之前检查至少有2行。
使用 glob 简化文件选择

import os
from tkinter import filedialog
from glob import glob
import os

source_folder = filedialog.askdirectory()

for file in glob(os.path.join(source_folder, '*.csv')):
    if file.lower().startswith('autopilot'):
        with open(file) as data:
            if len(rows := data.readlines()) > 1:
                print(rows[1])

字符串

相关问题