Python CSV模块始终需要文件路径?自动化?
为什么打开文件、读取文件、关闭文件时不会出错。“文件名”错误不存在。如何避免每次使用csv模块时都需要输入文件路径?在不需要文件路径的情况下,是否无法让脚本循环通过csv文件的目录Python CSV模块始终需要文件路径?自动化?,python,csv,Python,Csv,为什么打开文件、读取文件、关闭文件时不会出错。“文件名”错误不存在。如何避免每次使用csv模块时都需要输入文件路径?在不需要文件路径的情况下,是否无法让脚本循环通过csv文件的目录 data = open(filename, "r") d = data.readlines() data.close() 但不是这个 import csv os.makedirs('filesplit', exist_ok=True) for csvfilename in os.listdir('.'):
data = open(filename, "r")
d = data.readlines()
data.close()
但不是这个
import csv
os.makedirs('filesplit', exist_ok=True)
for csvfilename in os.listdir('.'):
if csvfilename.endswith('.csv'):
continue
csv_contents = []
csvfileobj = open (filename, 'r')
由于Python中文件对象的性质,必须始终指定路径。但是,路径只是一个字符串,因此您可以编写脚本来查找当前目录中的所有文件(使用
os
模块),过滤扩展名为.csv
的文件,并将其放入列表中。下面是一个例子:
from os import listdir
import csv
# Get the list of all files/directories in current path
all_files = listdir('.')
# Filter out only the .csv files
csv_files = [file for file in all_files if file.endswith('.csv')]
print csv_files
# Create file objects and csv objects for each CSV
file_objects = [open(file) for file in csv_files]
csv_readers = [csv.reader(csvfile) for csvfile in file_objects]
# Do what you need to do with the data
# Close file objects
for file in file_objects:
file.close()
…什么?如果需要访问文件,则需要知道其路径。不管它是否是csv文件。你能把你的问题编辑成包括你想要完成的事情吗?也许我们可以帮忙。你知道缩进在Python中很重要吗?你明白“继续”是什么意思吗?为什么你不使用csv模块却抱怨它?顺便说一句,你得到的错误与所有这些无关。