【问题标题】:smarter way of reading from a .txt file (for-loop?)从 .txt 文件中读取的更智能方式(for-loop?)
【发布时间】:2018-11-07 20:32:43
【问题描述】:

我正在读取包含一行文本 (YPerson18) 的 .txt 文件,我想知道是否有更聪明的方法来编写此代码,最好使用 for 循环。

import os

parent_dir = "../dirfiles"
os.chdir(parent_dir)

file_name = "userdata.txt"
append_mode = "a"
read_mode = "r"

read_file = open(file_name, read_mode)

the_lines = read_file.read(1)
print("Initial of the first name is: {}".format(the_lines))

the_lines = read_file.read(6)
print("The last name is: {}".format(the_lines))

the_lines = read_file.read(8)
print("The age is: {}".format(the_lines))

read_file.close()

输出应该是什么样子:

Initial of the first name is: Y
The last name is: Person
The age is: 18

【问题讨论】:

  • 如果它只有一行,你为什么需要一个循环?
  • 为什么不用 csv 模块?
  • @mad_:输入不是逗号分隔的,也不是任何东西分隔的。
  • 读取该行并使用正则表达式将其拆分。
  • @user2357112 我们仍然可以指定使用哪个分隔符。虽然我认为在这种情况下简单的读取就足够了,并且(如果有多行)循环遍历它

标签: python file for-loop operating-system


【解决方案1】:

您可以将整个文件读入一个字符串变量,然后使用切片表示法获取其中的一部分。

with read_file = open(file_name, read_mode):
    line = read_file.read().strip()
    initial = line[0]
    last_name = line[1:7]
    age = int(line[7:])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2016-06-15
    相关资源
    最近更新 更多