Python,从文件中一行一行读取

标签 python

我正在制作一个程序来区分有效和无效的社会安全号码。

该程序应该能够对我计算机上的文本文件中的数字进行排序。但是我只能一次输入所有数字(我认为)。我不会让程序一一检查数字。

这就是现在的样子

def fileinput():
    try:
        textfile = open("numberlist.txt","r")
        socialsecuritynumber = textfile.read()
        numberprogram(socialsecuritynumber)
    except IOError:
        print("there's no such file!\n")

有人知道我该怎么做吗? 文本文件仅包含数字

  • 1993-06-11 5570
  • 930611-5570
  • 930611 5570
  • 93 05115570
  • 1993年05月11日55月70日
  • 1993 05 11 5570

这是我的文本文件中的数字

最佳答案

  1. 始终使用 with 读取文件陈述。因此,如果读取过程中出现问题,或者代码块中出现异常,文件将自动关闭。
  2. 然后使用for循环像这样逐行读取

    with open("numberlist.txt","r") as textfile:
        for line in textfile:
            print line
    

关于Python,从文件中一行一行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20494832/

相关文章:

python - 使用 python 正则表达式进行双字母匹配

python - 在 Python 中将两个数组 append 在一起

python - XlsxWriter 和 Python 继承

python - 从嵌套字典创建多列 Pandas DataFrame

python - 从字典列表中获取键值

python - Pandas 重命名操作更改两列而不是一列上的列名称

python - Robot Framework导入库实例不包含定义的方法

python - Pandas 的 pd.NA 与 np.nan

python - 我无法使用 python-apt 获取 'required_changes'

Python Airflow 自定义传感器 - 实现哪些方法