python读取文本文件到数组并编辑数组

时间:2013-12-30 16:47:42

标签: python arrays join add

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

管理员 管理员 ADM 日志 登录

得到这行后我想添加(.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"

3 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

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()

答案 1 :(得分:0)

此代码:

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 :(得分:0)

我想这应该可行。

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")