歡迎您光臨本站 註冊首頁

python文件操作seek()偏移量,讀取指正到指定位置操作

←手機掃碼閱讀     ml5rwbikls @ 2020-07-06 , reply:0

python 文件操作seek() 和 telll() 自我解釋

file.seek()方法格式: seek(offset,whence=0) 移動文件讀取指針到制定位置

offset:開始的偏移量,也就是代表需要移動偏移的字節數。

whence: 給offset參數一個定義,表示要從哪個位置開始偏移;0代表從文件開頭算起,1代表開始從當前位置開始算起,2代表從文件末尾開始算起。當有換行時,會被換行截斷。  seek()無返回值,故值為None

tell() : 文科文件的當前位置,即tell是獲取文件指針位置。

readline(n):讀入若干行,n代表讀入的最長字節數。

readlines() :讀入所有行的內容

read讀入所有行的內容

tell() : 返回文件讀取指針的位置

補充知識:python中limit()和offset()的用法

limit()限制結果集每次值查詢幾條數據 offset()可以限制查找對象數據的時候過濾掉多少條切片,可以對Query對象使用切片操作,來獲取想要的數據,可以使用 select(start,stop)方法來求片操作,也可以使用'[start:stop]的方式來進行切片操作,

在實際開發中,中括號形式的是用處較多的,希望大家掌握

  #encoding: utf-8    from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,    DateTime  from sqlalchemy.ext.declarative import declarative_base  from sqlalchemy.orm import sessionmaker  from random import randint  from datetime import datetime    HOSTNAME = &#x27;127.0.0.1&#x27;  PORT = 3306  DATABASE = &#x27;first_sqlalchemy&#x27;  USERNAME = &#x27;root&#x27;  PASSWORD = &#x27;123456&#x27;    #dialect+driver://username:password@host:port/database  DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/"        "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)    engine = create_engine(DB_URI)  Base = declarative_base(engine)    # Session = sessionmaker(engine)  # session = Session()  session = sessionmaker(engine)() #Session(**local_kw)    class Article(Base):    __tablename__ = &#x27;article&#x27;    id = Column(Integer,primary_key=True,autoincrement=True)    title = Column(String(50),nullable=False)    create_time = Column(DateTime,default=datetime.now)      def __repr__(self):      return &#x27;<article:{title}>&#x27;.format(title=self.title)    # Base.metadata.drop_all()  #  # Base.metadata.create_all()  #  #  # for x in range(0,100):  #   article = Article(title = &#x27;title%s&#x27;%x)  #   session.add(article)  # session.commit()    #第一limit的用法,限制查詢多少數據  article = session.query(Article).limit(10).all()#用limit限制只查詢10個數據  print(article)    #第二個參數offset的用法,本意是偏移量,在這裡就是從多少開始查詢  article_offset = session.query(Article).offset(10).all()  print(article_offset)    #offset和limit聯合起來用,就相當於python 的字符串和列表、元祖的切片操作  article_offset_limit = session.query(Article).offset(10).limit(5).all()  print(article_offset_limit)    #如果查詢最新的10篇文章,就可以用order_by 和 limit 一起用  article_order_by_limit = session.query(Article).order_by(Article.id.desc()).limit(10).all()  print(article_order_by_limit)    #slice,本身就是切片的意思  article_order_by_slice = session.query(Article).order_by(Article.id.desc()).slice(0,10).all()  print(article_order_by_slice)    #還有一個更簡單的方法,就想python的列表切片操作    article_list_slice = session.query(Article).order_by(Article.id.desc())[0:10]  print(article_list_slice)

[ml5rwbikls ] python文件操作seek()偏移量,讀取指正到指定位置操作已經有228次圍觀

http://coctec.com/docs/python/shhow-post-241472.html