尝试让Python读取特定的CSV文件

问题描述 投票:0回答:1

我目前正在尝试编写一个程序,该程序将显示目录中的 CSV,然后您可以输入文件的编号,它将显示 .CSV 文件中写入的内容。我已经完成了所有工作,除了当我输入一个数字时,它会显示该 CSV 中写入的内容,然后显示其后的所有 CSV。

def seeProject():
    y = 1
    p = 0
    for x in os.listdir():
        if x.endswith(".csv"):
            print(str(y)+". "+ x)
            y = y+1
    f = input("Which would you like to open?\n")
    for x in os.listdir():
        if x.endswith (".csv") and p == int(f):
            j = open(x,"r")
            for w in j:
                print(w)
        else:
            p += 1
            continue

我尝试更改 p 值,但没有成功。我确实尝试过按名称打开特定文件,这很有效,但未来的一些文件名称非常长,我宁愿只选择文件号。当我输入 1 时,我得到:

1. Herman.csv
2. Jemma.csv
Which would you like to open?
1
EROEIER,EEROIWEN,EOTIHNWET,0,WOIRH(*,WHR(*WR,WRUIWRH8,WRHWR*

WRWRIUWBT,OIEGE,EPORTE(Tb,0,OEIRHWER(,WER(*WE,WBRUI8,IWBR8

输入 2 让我:

1. Herman.csv
2. Jemma.csv
Which would you like to open?
2
WRWRIUWBT,OIEGE,EPORTE(Tb,0,OEIRHWER(,WER(*WE,WBRUI8,IWBR8
``
python read.csv python-3.12
1个回答
0
投票

问题是您仅针对非 CSV 文件递增

p
。但你的整个方法比需要的要复杂得多。

将所有 CSV 文件放入列表中,您可以使用

glob.glob()
轻松完成此操作。然后打印列表以创建菜单,并使用用户的输入作为列表的索引。

import glob

def seeProject():
    csv_files = glob.glob("*.csv")
    for i, filename in enumerate(csv_files, 1):
        print(f'{i}. {filename}')

    while True:
        f = int(input("Which would you like to open?\n"))
        if 1 <= f <= len(csv_files):
            break
        print(f"Enter a number between 1 and {len(csv_files)}")
    filename = csv_files[f-1]
    with open(filename, "r") as file:
        for line in f:
            print(line)
© www.soinside.com 2019 - 2024. All rights reserved.