如何从文件夹中获取所有文件并使用python存储它? 此代码查找文件
# list of dir
list_of_dir = os.listdir(dir_loc)
print(list_of_dir)
我如何存储这些文件? 文件类型可以是jpeg,png,txt,csv。我需要将所有文件上传到数据库(mongodb)
答案 0 :(得分:2)
我们列出当前目录并打印内容您可以对读取文件执行其他操作,即操作
import os
dir_loc = os.getcwd()
list_of_dir = os.listdir(dir_loc)
for file in list_of_dir:
with open(file, 'rb') as f:
temp_file = f.read()
# Do somethin with the file, it's currently stored in a variable
print(temp_file) # I used print
Pymongo :
import os
import pymongo
import gridfs
dir_loc = os.getcwd()
list_of_dir = os.listdir(dir_loc)
# Pymongo
connection = pymongo.Connection("localhost", 27017)
db = connection.yourdatabase
# Create a GridFS object using a reference to the database in which to
# store the file(s).
gridFs = gridfs.GridFS(db)
for file in list_of_dir:
with open(file, 'rb') as f:
file_id = gridFs.put(f.read(), filename="my_file_name")
答案 1 :(得分:-1)
您只需使用以下代码将其存储到txt
文件:
with open("somefile.txt", 'w') as f:
f.write(str().join([filename+'\n' for filename in filenames]))