Tan*_*ikh 13 python google-app-engine file
我有一个脚本,我想检查存储桶中是否存在文件,如果没有,则创建一个.
我试过用os.path.exists(file_path)哪里file_path = "/gs/testbucket".但我得到一个文件未找到错误.
我知道我可以使用files.listdir()API函数列出位于路径中的所有文件,然后检查我想要的文件是否是其中之一.但我想知道是否有另一种方法来检查文件是否存在.
nic*_*eak 14
这篇文章是旧的,你现在可以使用blob类检查GCP上是否存在文件,但是因为我花了一些时间才找到答案,所以在这里为其他正在寻找解决方案的人添加
from google.cloud import storage
name = 'file_i_want_to_check.txt'
storage_client = storage.Client()
bucket_name = 'my_bucket_name'
bucket = storage_client.bucket(bucket_name)
stats = storage.Blob(bucket=bucket, name=name).exists(storage_client)
Run Code Online (Sandbox Code Playgroud)
文档在这里
希望这可以帮助!
小智 10
@nickthefreak 提供的答案是正确的,Om Prakash 的评论也是正确的。另一个注意事项是bucket_name 不应包含gs://在前面或/末尾。
附上@nickthefreak 的例子和 Om Prakash 的评论:
from google.cloud import storage
name = 'folder1/another_folder/file_i_want_to_check.txt'
storage_client = storage.Client()
bucket_name = 'my_bucket_name' # Do not put 'gs://my_bucket_name'
bucket = storage_client.bucket(bucket_name)
stats = storage.Blob(bucket=bucket, name=name).exists(storage_client)
Run Code Online (Sandbox Code Playgroud)
stats 将是一个布尔值(True 或 False),具体取决于文件是否存在于存储桶中。
(我没有足够的声望点来评论,但我想为其他人节省一些时间,因为我在这上面浪费了太多时间)。
就像在blob对象中使用exist方法一样简单:
from google.cloud import storage
def blob_exists(projectname, credentials, bucket_name, filename):
client = storage.Client(projectname, credentials=credentials)
bucket = client.get_bucket(bucket_name)
blob = bucket.blob(filename)
return blob.exists()
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您正在寻找 NodeJS 中的解决方案,那么这里是:
var storage = require('@google-cloud/storage')();
var myBucket = storage.bucket('my-bucket');
var file = myBucket.file('my-file');
file.exists(function(err, exists) {});
// If the callback is omitted, then this function return a Promise.
file.exists().then(function(data) {
var exists = data[0];
});
Run Code Online (Sandbox Code Playgroud)
如果您需要更多帮助,可以参考此文档:https : //cloud.google.com/nodejs/docs/reference/storage/1.5.x/File#exists
我想没有函数可以直接检查给定路径的文件是否存在。
我创建了一个函数,它使用files.listdir()API 函数列出存储桶中的所有文件,并将其与我们想要的文件名进行匹配。如果找到则返回 true,如果未找到则返回 false。