python - 将整个文件作为一个字符串导入

标签 python bash postgresql psql

如何将整个文件作为一个字符串导入 PostgreSQL?

create table text_files (
  id serial primary key,
  file_content text
);

我尝试过 \copy text_files (file_content) from/home/test.txt,但这会在文本文件中每行创建一行。

我有数百个小文本文件,我想使用一些 bash 循环,其中包含 \copy

更新:如果 bash 和 \copy 不是完成此任务的最佳工具集,我可以使用其他编程语言 - 也许 Python 可以提供一些东西。

最佳答案

如果您确实必须在 bash 中执行此操作,则需要手动执行:

psql regress -c "insert into text_files(file_content) values ('$(sed "s/'/''/g" test.txt)');"

但它会有点脆弱。我个人建议使用更复杂的脚本语言。它还会将整个文件加载到内存中至少几次。

psql\lo_import,但它将文件导入到 pg_largeobject,而不是 text 字段。

关于python - 将整个文件作为一个字符串导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21514971/

相关文章:

windows - 如何将文本从 Windows 中的 Firefox 复制到 Unix 中的 bash shell?

regex - 将正则表达式匹配绑定(bind)到bash中的变量

postgresql - 错误 : COPY delimiter must be a single one-byte character

PostgreSQL:如何在不使用 "column definition list"的情况下从表中返回动态行?

python - 如何从 Pyramid 内提供 wsgi 应用程序?

python - Snakemake - 尝试使用 global_wildcards 时出现问题(TypeError : expected str, 获取列表)

python - Spyder IDE 自动缩进

python - 在 Jupyter Lab 中,在 Python 控制台中执行编辑器代码

linux - BASH Shell 交互式 session - 如何修复 ASCII 艺术动画输出?

postgresql - AWS Lambda 导入 psycopg2 - 无法导入模块 'app' : No module named 'psycopg2. _psycopg