加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

带枚举的基本python file-io变量

发布时间:2020-12-20 12:26:55 所属栏目:Python 来源:网络整理
导读:python的新手,并试图学习文件i / o的绳索. 我正在使用以下格式从大型(200万行)文件中提取行: 56fr44543d4343d5irh3 这是我用来返回代码的函数: def getCode(i): with open("test.txt") as f: for index,line in enumerate(f): if index == i: code = # wha
python的新手,并试图学习文件i / o的绳索.

我正在使用以下格式从大型(200万行)文件中提取行:

56fr4
4543d
4343d
5irh3

这是我用来返回代码的函数:

def getCode(i):
    with open("test.txt") as f:
        for index,line in enumerate(f):
            if index == i:
                code = # what does it equal?
                break
    return code

一旦索引到达正确的位置(i),我使用什么语法来设置代码变量?

解决方法

code = line.strip()

将删除尾随的新行时,将代码分配给等于i的行号.

您还需要稍微更新您的代码

def getCode(i):
    with open('temp.txt','r') as f:
             for index,line in enumerate(f):
                     if index == i:
                             code = line.strip()
                             return code

为什么你需要.strip()

>>> def getCode(i):
...     with open('temp.txt') as f:
...             for index,line in enumerate(f):
...                     if index == i:
...                             code = line
...                             return code
 ... 
>>> getCode(2)
"                  'LINGUISTIC AFFILIATION',n"

是的,“’LINGUISTIC AFFILIATION’,”是我目前的temp.txt’

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读