【发布时间】:2023-03-09 03:40:01
【问题描述】:
我正在尝试使用 for 循环遍历目录中的 csv 文件,并使用预定义的函数对其进行处理。
# Define a function to collect form page data and save as a new csv file
def writeFormPage(file, path):
'''
Input:
Index CSV
Output:
Page CSV
'''
with open(file, 'r') as rf:
reader = csv.reader(rf)
base_name = os.path.basename(file)
file_path = os.path.join(path, base_name)
with open(file_path, 'w') as wf:
writer = csv.writer(wf, delimiter = ',')
for line in reader:
url = line[-1]
page_data = (parseFormPage(url))
writer.writerow(page_data)
time.sleep(3 + random.random() * 3)
# Create a new directory to save new CSV files
page_dir = './page'
if not os.path.isdir(page_dir):
os.makedirs(page_dir)
os.path.isdir(page_dir)
for filename in os.listdir(indx_dir):
if filename.endswith('.csv'):
writeFormPage(filename, page_dir)
time.sleep(3 + random.random() * 3)
FileNotFoundError Traceback (most recent call last)
<ipython-input-23-3a8a501dd2e9> in <module>
1 for filename in os.listdir(indx_dir):
2 if filename.endswith('.csv'):
----> 3 writeFormPage(filename, page_dir)
4 time.sleep(3 + random.random() * 3)
<ipython-input-22-0fc6fceffe13> in writeFormPage(file, path)
7 Page CSV
8 '''
----> 9 with open(file, 'r') as rf:
10 reader = csv.reader(rf)
11
FileNotFoundError: [Errno 2] No such file or directory: '2007Q2.csv'
错误命名了一个我没有特别命名的文件,这让我想知道为什么它说找不到文件。提到的文件是我要迭代的目录中的第一个文件。 第一个代码块中的预定义函数是合理的,我已经使用单个 csv 文件对其进行了测试。我只是在循环中挣扎。我是初学者,老实说,这些循环似乎是我的克星,它们让我头疼了好几个小时! 如果有人可以提供帮助,我将不胜感激。
【问题讨论】:
-
"listdir" 只返回没有路径的文件名,但 "open" 然后使用当前工作目录。使用“os.path.join”或“pathlib”构建完整路径。
-
你需要
fullpath = os.path.join(indx_dir, filename) -
@furas 谢谢你们的回复。这个论点需要去哪里?我认为我理解这个概念,但还不足以知道它将与哪个部分相关。我尝试将
fullpath代码添加到最后一段代码中的几个位置,但没有任何作用。 -
您必须将
fullpath发送到writeFormPage(fullpath, ...),因此您必须在与writeFormPage对齐之前创建它
标签: python csv for-loop iteration