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

2024-04-25 20:35:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

管理员 管理员 行政长官 日志 登录

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

Tags: 数据pathinforos管理员line数组
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()

此代码:

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

产生:

^{pr2}$

我想这应该行得通。在

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

相关问题 更多 >

    热门问题