如何格式化文本文件中的列表?

时间:2016-12-08 16:38:06

标签: python text text-files

我有一个如下文本文件

  

Mo,M,15,

     

Jen,F,14

下面的代码替换了“Mo”的年龄

newAge = "20"
result = ""
with open("file.txt") as f:
for line in f:
   if line.lower().startswith( "mo," ):
       list = line.split() 
       list[2] = str( newAge )
       line = ", ".join( list )
   result += line + '\n'
f = open("file.txt", 'w') 
f.write(result)
f.close()

以后的文件怎么样?

  

[, '...,M ,,ö,, M,2,...,0 ,,',]

如何将其格式化为:

  

Mo,M,20,

5 个答案:

答案 0 :(得分:1)

使用csv模块读取和写入文件。以下是经过测试的示例。

newAge = ' 20'
result = []
with open('file.txt','rb') as fin, open('file_out.txt','wb') as fou:
    cr = csv.reader(fin)
    cw = csv.writer(fou)
    for line in cr:
        if line[0].lower() == "mo":
            line[2] = newAge
        cw.writerow(line)

答案 1 :(得分:0)

像@azalea提到的那样,使用.split(',')。此外,您应该只对您构建的字符串使用换行符,因为现有字符串已包含新行。

newAge = "20"
result = ""
with open("file.txt") as f:
    for line in f:
        if line.lower().startswith("mo"):
            list = line.split(', ')
            list[2] = str(newAge)
            line = ", ".join(list) + '\n'
        result += line
f = open("file2.txt", 'w')
f.write(result)
f.close()

答案 2 :(得分:0)

您可以尝试这样做:

newAge = "20"
result = ""
with open("file.txt") as f:
    for line in f:
        if line.lower().startswith( "mo," ):
            list = line.split() 
            list[2] = newAge
            line = ''
            for element in list:
                line += str(element)
                line += ', '
        result += line + '\n'
with open('file.txt', 'w') as inf:
    inf.write(result)

如果您特别关注最后一个元素末尾的空格,您甚至可以这样做:

newAge = "20"
result = ""
with open("file.txt") as f:
    for line in f:
        if line.lower().startswith( "mo," ):
            list = line.split() 
            list[2] = newAge
            line = ''
            for index, element in enumerate(list):
                line += str(element)
                if not index is len(list) -1:
                    line += ', '
                else:
                    line += ','
        result += line + '\n'
with open('file.txt', 'w') as inf:
    inf.write(result)

答案 3 :(得分:0)

你用空格分割线......然后你应该用空格加入它!

newAge = "20"
result = ""
with open("file.txt") as f:
    for line in f:
       if line.lower().startswith( "mo," ):
           list = line.split() 
           list[2] = str( newAge )
           line = " ".join( list )+"\n"
       result += line
f = open("file.txt", 'w') 
f.write(result)
f.close()

答案 4 :(得分:0)

我更喜欢保持简单。只需使用字符串模块。 你可以这样使用它。

int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num) + 1;

我希望这有帮助!