【发布时间】: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