利用python将excel文件转成txt文件,再将txt文件上传hdfs,最后传入hive中

将excel文件转成txt文件,再将txt文件上传hdfs,最后传入hive中

注意的点
(1)先判断写入的txt文件是否存在,如果不存在就需要创建路径
(2)如果txt文件已经存在,那么先将对应的文件进行删除后再写入txt数据
(3)excel文件中有可能第一行是字段名,需要跳过
1.利用python将excel转成txt文件

from datetime import datetime, timedelta
import os
import pytz
import pandas as pd

def excel_to_txt(name, date):
    # Read Excel file into a DataFrame
    df = pd.read_excel(f'data/excel/{name}.xlsx', header=None, skiprows=1)

    # Define output directory and path
    output_directory = os.path.join('data', 'txt', date)
    os.makedirs(output_directory, exist_ok=True)  # Create directory if it doesn't exist
    output_path = os.path.join(output_directory, f'{name}.txt')

    # Check if the file already exists, if so, remove it
    if os.path.exists(output_path):
        os.remove(output_path)
        print(f'Existing file {output_path} removed.')

    # Write DataFrame to a new text file
    print('开始写入txt文件')
    df.to_csv(output_path, header=None, sep='\t', index=False)
    print('文件写入成功!')
    return output_path



if __name__ == '__main__':
    current_time = datetime.now(pytz.timezone('Asia/Shanghai'))
    one_day_ago = (current_time - timedelta(days=1)).strftime('%Y-%m-%d')
    local_file_path = excel_to_txt('IS_GS_Recruitment_Data_20231211', one_day_ago)
    print(local_file_path)

2.上传到hdfs
3.在hive中创建表

drop table if exists ticket.test_text;
create external table IF NOT EXISTS ticket.test_text
(
    name string,
    age int
) comment ''
      row format delimited fields terminated by '\t'
    lines terminated by '\n'
    NULL DEFINED AS ''
    stored as textfile
    LOCATION '/warehouse/ticket/ods/test_text';

4.将hdfs数据写入hive

load data inpath '/origin_data/test.txt' overwrite into table ticket.test_text;

相关推荐

  1. 如何txt文件导入hive

    2024-01-04 11:34:05       11 阅读
  2. pythonExcel文档.db数据库文件

    2024-01-04 11:34:05       37 阅读
  3. python.db数据库文件Excel文档

    2024-01-04 11:34:05       32 阅读
  4. python输出保存到txt文档

    2024-01-04 11:34:05       19 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-04 11:34:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-04 11:34:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-04 11:34:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-04 11:34:05       18 阅读

热门阅读

  1. Mybatis-plus分页插件PageHelper的两种不同使用方式

    2024-01-04 11:34:05       35 阅读
  2. Django定制模型管理器

    2024-01-04 11:34:05       45 阅读
  3. Python Pillow (PIL) 库简介

    2024-01-04 11:34:05       37 阅读
  4. 当前IoT(物联网)的发展趋势

    2024-01-04 11:34:05       38 阅读
  5. SSD的接口及协议

    2024-01-04 11:34:05       38 阅读
  6. 【Hadoop-HDFS-S3】HDFS 和存储对象 S3 的对比

    2024-01-04 11:34:05       31 阅读