小编Lea*_*wly的帖子

Python MySQL连接器 - 使用fetchone时发现未读结果

我将JSON数据插入MySQL数据库

我正在解析JSON,然后使用python连接器将其插入MySQL数据库

通过试用,我可以看到错误与这段代码有关

for steps in result['routes'][0]['legs'][0]['steps']:
    query = ('SELECT leg_no FROM leg_data WHERE travel_mode = %s AND Orig_lat = %s AND Orig_lng = %s AND Dest_lat = %s AND Dest_lng = %s AND time_stamp = %s')
    if steps['travel_mode'] == "pub_tran":
        travel_mode = steps['travel_mode']
        Orig_lat = steps['var_1']['dep']['lat']
        Orig_lng = steps['var_1']['dep']['lng']
        Dest_lat = steps['var_1']['arr']['lat']
        Dest_lng = steps['var_1']['arr']['lng']
        time_stamp = leg['_sent_time_stamp'] 
    if steps['travel_mode'] =="a_pied":
        query = ('SELECT leg_no FROM leg_data WHERE travel_mode = %s AND Orig_lat = %s AND Orig_lng = %s …
Run Code Online (Sandbox Code Playgroud)

python mysql

37
推荐指数
3
解决办法
6万
查看次数

使用Lambda从S3读取数据

我在AWS上的S3存储桶中存储了一系列json文件.

我希望使用AWS lambda python服务来解析此json并将解析后的结果发送到AWS RDS MySQL数据库.

我有一个稳定的python脚本,用于解析和写入数据库.我需要lambda脚本来遍历json文件(当它们被添加时).

每个json文件都包含一个简单的列表 results = [content]

在伪代码中我想要的是:

  1. 连接到S3存储桶(jsondata)
  2. 阅读JSON文件的内容(results)
  3. 为此数据执行我的脚本(results)

我可以列出我所拥有的桶:

import boto3

s3 = boto3.resource('s3')

for bucket in s3.buckets.all():
    print(bucket.name)
Run Code Online (Sandbox Code Playgroud)

赠送:

jsondata
Run Code Online (Sandbox Code Playgroud)

但我无法访问此存储桶来读取其结果.

似乎没有readload功能.

我希望有类似的东西

for bucket in s3.buckets.all():
   print(bucket.contents)
Run Code Online (Sandbox Code Playgroud)

编辑

我误解了一些事情.lambda必须自己下载,而不是在S3中读取文件.

这里看来,你必须给lambda一个下载路径,从中可以访问文件本身

import libraries

s3_client = boto3.client('s3')

def function to be executed:
   blah blah

def handler(event, context):
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key'] 
        download_path = '/tmp/{}{}'.format(uuid.uuid4(), key) …
Run Code Online (Sandbox Code Playgroud)

python json amazon-s3 amazon-web-services aws-lambda

31
推荐指数
2
解决办法
5万
查看次数

Git lfs - "这超过了GitHub的文件大小限制为100.00 MB"

我有一些csv文件大于github的文件大小限制为100.00 MB.我一直在尝试使用Git Large File Storage扩展.

https://git-lfs.github.com/

来自LFS - "Large file versioning- Version large files—even those as large as a couple GB in size—with Git."

我在关注的文件夹中应用了以下内容:

git lfs track "*.csv"
Run Code Online (Sandbox Code Playgroud)

但是,当我推:

remote: error: File Time-Delay-ftn/Raw-count-data-minor-roads1.csv is 445.93 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File Time-Delay-ftn/Raw-count-data-major-roads.csv is 295.42 MB; this exceeds GitHub's file size limit of 100.00 MB
Run Code Online (Sandbox Code Playgroud)

当我查看有问题的文件夹时:

-rw-r-----   1 user  staff    42B 23 Oct 12:34 .gitattributes
-rw-r--r--   1 user  staff   1.3K 19 Oct 14:32 …
Run Code Online (Sandbox Code Playgroud)

git github large-files git-lfs

27
推荐指数
9
解决办法
3万
查看次数

CSV读取错误:在未加引号的字段中看到的换行符

我创建了一个python脚本,它与10个记录的测试CSV数据集一起使用.当我将其扩展到实际数据集(几千行)时,我收到以下错误:

_csv.Error:在未引用字段中看到的换行符 - 是否需要以通用换行模式打开文件?

代码如下:

with open('./Origins.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    origincoords = ['{Y},{X}'.format(**row) for row in reader]
Run Code Online (Sandbox Code Playgroud)

完整的错误代码是:

Traceback (most recent call last):
  File "./Driving.py", line 14, in <module>
    origincoords = ['{Y},{X}'.format(**row) for row in reader]
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 103, in next
    self.fieldnames
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 90, in fieldnames
    self._fieldnames = self.reader.next()
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
Run Code Online (Sandbox Code Playgroud)

也许我正在使用的CSV读取方法存在规模问题?

python csv

15
推荐指数
1
解决办法
2万
查看次数

低InnoDB每秒写入 - 使用Python将AWS EC2写入MySQL RDS

我有大约60GB的JSON文件,我使用Python解析,然后使用Python-MySQL Connector插入MySQL数据库.每个JSON文件大约500MB

我一直在使用带有辅助卷的AWS r3.xlarge EC2实例来保存60GB的JSON数据.

然后我使用AWS RDS r3.xlarge MySQL实例.这些实例都位于相同的区域和可用区域中.EC2实例使用以下Python脚本加载JSON,解析它然后将其插入MySQL RDS.我的python:

import json
import mysql.connector
from mysql.connector import errorcode
from pprint import pprint
import glob
import os

os.chdir("./json_data")

for file in glob.glob("*.json"):
    with open(file, 'rU') as data_file:
        results = json.load(data_file)
        print('working on file:', file)

    cnx = mysql.connector.connect(user='', password='',
        host='')

    cursor = cnx.cursor(buffered=True)

    DB_NAME = 'DB'

    def create_database(cursor):
        try:
            cursor.execute(
                "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
        except mysql.connector.Error as err:
            print("Failed creating database: {}".format(err))
            exit(1)

    try:
        cnx.database = DB_NAME    
    except mysql.connector.Error …
Run Code Online (Sandbox Code Playgroud)

python mysql amazon-ec2 amazon-web-services

15
推荐指数
1
解决办法
398
查看次数

用Apache Spark读取JSON - `corrupt_record`

我有一个json文件,nodes看起来像这样:

[{"toid":"osgb4000000031043205","point":[508180.748,195333.973],"index":1}
,{"toid":"osgb4000000031043206","point":[508163.122,195316.627],"index":2}
,{"toid":"osgb4000000031043207","point":[508172.075,195325.719],"index":3}
,{"toid":"osgb4000000031043208","point":[508513,196023],"index":4}]
Run Code Online (Sandbox Code Playgroud)

我能够使用Python读取和操作此记录.

我试图scala通过这个读取此文件spark-shell.

从这个教程中,我可以看到,它可以读取json通过sqlContext.read.json

val vfile = sqlContext.read.json("path/to/file/nodes.json")
Run Code Online (Sandbox Code Playgroud)

但是,这会导致corrupt_record错误:

vfile: org.apache.spark.sql.DataFrame = [_corrupt_record: string]
Run Code Online (Sandbox Code Playgroud)

任何人都可以对这个错误有所了解吗?我可以阅读和使用该文件与其他应用程序,我相信它没有腐败和声音json.

json scala apache-spark

15
推荐指数
3
解决办法
2万
查看次数

从JSON到JSONL的Python转换

我希望将标准JSON对象处理为一个对象,其中每行必须包含一个单独的,自包含的有效JSON对象。查看JSON行

JSON_file =

[{u'index': 1,
  u'no': 'A',
  u'met': u'1043205'},
 {u'index': 2,
  u'no': 'B',
  u'met': u'000031043206'},
 {u'index': 3,
  u'no': 'C',
  u'met': u'0031043207'}]
Run Code Online (Sandbox Code Playgroud)

To JSONL

{u'index': 1, u'no': 'A', u'met': u'1043205'}
{u'index': 2, u'no': 'B', u'met': u'031043206'}
{u'index': 3, u'no': 'C', u'met': u'0031043207'}
Run Code Online (Sandbox Code Playgroud)

我当前的解决方案是将JSON文件读取为文本文件,并[从开头和]结尾删除。因此,在每行上创建一个有效的JSON对象,而不是在包含行的嵌套对象上创建一个有效的JSON对象。

我想知道是否有更优雅的解决方案?我怀疑在文件上使用字符串操作可能会出错。

目的是json在Spark上将文件读入RDD。查看相关问题- 使用Apache Spark读取JSON-`corrupt_record`

python json

10
推荐指数
3
解决办法
7999
查看次数

Git BFG追溯性地启用LFS保护的提交问题

我有大文件,并试图使用新的Git LFS系统.

我发布了这个问题 - Git lfs - "这超出了GitHub的文件大小限制为100.00 MB"

爱德华汤姆森正确地确定了我的问题 - 你不能追溯使用LFS.他建议我使用BFG LFS支持

这在一定程度上起了作用.绝大多数文件都被更改了.但是,有一些未经修改的受保护提交.

在这些受保护的提交中,有些超过100.00MB,因此导致github出现远程:错误

Protected commits
-----------------

These are your protected commits, and so their contents will NOT be altered:

 * commit c7cd871b (protected by 'HEAD') - contains 165 dirty files :
    - Directions_api/Applications/LTDS/Cycling/Leisure/l__cyc.csv (147.3 KB)
    - Directions_api/Applications/LTDS/Cycling/Work/w_cyc.csv (434.0 KB)
    - ...

WARNING: The dirty content above may be removed from other commits, but as
the *protected* commits still use it, it will STILL exist in your repository. …
Run Code Online (Sandbox Code Playgroud)

git github bfg-repo-cleaner

8
推荐指数
1
解决办法
1546
查看次数

ggplot python以小时分辨率处理数周的时间数据

我正按照每小时的分辨率绘制一系列道路的行程时间,数周时间.

我可以使用unix时间绘图,但这不是很直观.这是7天的数据.

在此输入图像描述

我使用一个函数来操作time字段以给出日期和小时:

def plot_time(time):
    return time.strftime('%Y-%m-%d-%H')
Run Code Online (Sandbox Code Playgroud)

但是,这会导致ggplot在尝试绘制时抛出值错误:

ValueError: invalid literal for float(): 2016-04-13-00
Run Code Online (Sandbox Code Playgroud)

是否有更简单的显示日期和一小时的方法?

或者,我可以在轴上用日期刻度绘制unix时间,但是在轴上有一些小时分辨率会很好.

python ggplot2 python-ggplot

7
推荐指数
1
解决办法
467
查看次数

查找具有部分字符串匹配的目录中的文件

我有一个目录,其中包含以下文件:

apple1.json.gz
apple2.json.gz
banana1.json.gz
melon1.json.gz
melon2.json.gz
Run Code Online (Sandbox Code Playgroud)

我希望能够找到所有的apple,bananamelon文件类型.

从这个SO答案我知道我可以通过文件类型找到:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.json.gz"):
    print(file)
Run Code Online (Sandbox Code Playgroud)

但是,就我而言,我无法通过文件名或文件类型进行匹配.而是一个部分文件名匹配(所有apple的等等)

在这个SO问题中,提出了这个解决方案:

[in] for file in glob.glob('/path/apple*.json.gz'):
    print file
Run Code Online (Sandbox Code Playgroud)

但是,这会返回零

[out]
     0
Run Code Online (Sandbox Code Playgroud)

python glob

6
推荐指数
1
解决办法
2万
查看次数