【问题标题】:Python - How to upload files created today in a folder to S3Python - 如何将今天在文件夹中创建的文件上传到 S3
【发布时间】:2017-09-22 22:44:53
【问题描述】:

我有一个名为myfolder 的文件夹,其中包含多个文件,文件名如下,

ID001_2017-04-15.csv, ID002_2017-04-15.csv, ID001_2017-04-16.csv, ID002_2017-04-16.csv, 
ID001_2017-04-17.csv, ID002_2017-04-17.csv, ID001_2017-04-18.csv, ID002_2017-04-18.csv

文件名上的日期是文件创建的日期。例如,文件ID001_2017-04-17.csv创建于2017-04-17。这是我将文件夹中的所有文件上传到 Amazon S3 的方法,

import boto3

def upload_files(path):
    session = boto3.Session(
              aws_access_key_id = 'this is my access key',
              aws_secret_access_key = 'this is my secret key',
              region_name = 'this is my region'
              )
    s3 = session.resource('s3')
    bucket = s3.Bucket('this is my bucket')

    for subdir, dirs, files in os.walk(path):
        for file in files:
            full_path = os.path.join(subdir, file)
            with open(full_path, 'rb') as data:
                bucket.put_object(Key = full_path[len(path) + 1:], Body = data)

if __name__ == "__main__":
    upload_files('path to myfolder') ## Replace this with your folder directory

我的问题是我只能将今天创建的文件上传到 Amazon S3 吗?

【问题讨论】:

  • 看看stackoverflow.com/questions/5141437/… - 并过滤今天的日期。
  • 如果您的目的是将文件从本地目录同步到 S3,您可以使用具有 aws s3 sync 命令的 AWS Command-Line Interface (CLI)。比编写自己的代码容易得多。
  • @JohnRotenstein 谢谢。是的,我想将文件从本地目录同步到 S3。是否可以使用 CLI 将今天生成的文件同步到 S3?
  • 为什么只想同步“今天的文件”?是不是因为您每天都上传文件而只想发送以前未上传的新文件?如果是这样,只需使用aws s3 sync - 它只复制自上次同步以来新的或更改的文件。
  • @JohnRotenstein 好的。我得到了它。非常感谢!

标签: python amazon-web-services amazon-s3 directory boto


【解决方案1】:

这将检查今天是否创建了文件:

import os.path
import datetime.datetime

# Create a datetime object for right now:
now = datetime.datetime.now()
# Create a datetime object for the file timestamp:
ctime = os.path.getctime('example.txt')
filetime = datetime.datetime.fromtimestamp(ctime)

# Check if they're the same day:
if filetime.year == now.year and filetime.month == now.month and filetime.day = now.day:
    print('File was created today')

如果您在 for file in files: 循环中添加类似内容,您应该能够隔离今天创建的文件。

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2018-04-28
    相关资源
    最近更新 更多