【问题标题】:python read text file to array and edit the arraypython读取文本文件到数组并编辑数组
【发布时间】:2013-12-30 16:47:42
【问题描述】:

大家好,我试图逐行读取文本文件,然后将所有数据存储到一个数组中,我想在数组的值中添加文本,例如

管理员 行政人员 管理员 日志 登录

得到这行后我想添加(.php) 最后

这是我的代码

current_folder= os.path.dirname(os.path.realpath(__file__))
current_list=str(current_folder)+"\pages.txt"

ins = open( current_list, "r" )
array = []
for line in ins:
    array.append(line.rstrip())

for fahad in array:

    array+".php"

【问题讨论】:

  • 您希望文件中的每个值还是整行都成为一个条目?例如array = ['admin', 'administrator', 'adm', 'log', 'login']array = ['admin administrator adm log login']
  • 在你最后的for lop 中有一个错误。将正文中的array 替换为fahad,它应该按照您希望的方式运行
  • 看起来你只是在谈论一个列表。在 Python 中,“数组”和“列表”意味着两个不同的东西。特别是,数组通常是同质集合。

标签: python arrays join add


【解决方案1】:

这段代码:

try:
    with open('test.txt', 'r') as ins: #Opens the file and closes it when Python is done with it
        array = []
        for line in ins:
            array.append(line.rstrip()) # appends each line of the file with trailing white space stripped

        for fahad in array:
            fahad += ".php" # for each item in the list 'array' it concatenates '.php' on to the end. The += operator is the same as fahad = fahad + '.php'
            print(fahad)

except FileNotFoundError: # this is part of a try/except block. If the file isn't found instead of throwing an error this will trigger. Right now nothing happens because of the pass statement but you can change that to print something if you like.
    pass

产生:

>>> fahad
'admin administrator adm log login.php'

【讨论】:

    【解决方案2】:

    我想这应该可行。

    current_folder= os.path.dirname(os.path.realpath(__file__))
    current_list=str(current_folder)+"\pages.txt"
    
    ins = open( current_list, "r" ).read().split()
    array = []
    for line in ins:
        array.append(line + ".php")
    

    【讨论】:

      【解决方案3】:

      你可以试试这个代码:

      ins = open( "hello.txt", "r" )
      array = []
      rows = ins.read().split('\n') #or \r\n - it depends from your txt
      for row in rows:
          array.append(row+".php")
      
      ins.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多