我必须访问CSV文件中的第N行.
这是我做的:
import csv
the_file = open('path', 'r')
reader = csv.reader(the_file)
N = input('What line do you need? > ')
i = 0
for row in reader:
if i == N:
print("This is the line.")
print(row)
break
i += 1
the_file.close()
Run Code Online (Sandbox Code Playgroud)
......但这并不是最佳的.编辑精度:如果文件很大,我不想遍历所有行,我不想将整个文件加载到内存中.
我确实希望reader[N]存在类似的东西,但我还没有找到它.
编辑答案:这一行(来自选择的答案)是我正在寻找的:
next(itertools.islice(csv.reader(f), N, None)
Run Code Online (Sandbox Code Playgroud) 我想从postgresql数据库中提取数据并在脚本中使用该数据(以数据帧格式).这是我最初的尝试:
from pandas import DataFrame
import psycopg2
conn = psycopg2.connect(host=host_address, database=name_of_database, user=user_name, password=user_password)
cur = conn.cursor()
cur.execute("SELECT * FROM %s;" % name_of_table)
the_data = cur.fetchall()
colnames = [desc[0] for desc in cur.description]
the_frame = DataFrame(the_data)
the_frame.columns = colnames
cur.close()
conn.close()
Run Code Online (Sandbox Code Playgroud)
注意:我知道我不应该使用"字符串参数插值(%)将变量传递给SQL查询字符串",但这对我来说非常有用.
会有更直接的方法吗?
编辑:这是我从所选答案中使用的内容:
import pandas as pd
import sqlalchemy as sq
engine = sq.create_engine("postgresql+psycopg2://username:password@host:port/database")
the_frame = pd.read_sql_table(name_of_table, engine)
Run Code Online (Sandbox Code Playgroud) 我在PyCharm中设置了一个远程解释器.
每次我关闭并重新打开PyCharm时,连接似乎都被打破了,"重新打开"连接的过程对我来说效率不高.
在执行以下操作之前,无法运行任何脚本.
这是我通常做的事情:
此时,我可以在远程计算机上运行任何脚本.
最好/最快的方法是什么?(以任何方式"保存设置"?)
python ×3
csv ×1
dataframe ×1
file ×1
interpreter ×1
pandas ×1
postgresql ×1
psycopg2 ×1
pycharm ×1
python-3.x ×1