简体   繁体   English

TypeError:write()参数必须是str,而不是写入文件时的列表

[英]TypeError: write() argument must be str, not list while writing to file

I wrote one program which help inrementing the digit in the file. 我写了一个程序,帮助修改文件中的数字。 Able to copy only first line if I am using writelines and for f.write I am getting 如果我正在使用writelines而且只能复制f.write ,我只能复制第一
f.write(new_line ) if lines[0].strip().endswith(':') else f.write([new_line, *lines]) TypeError: write() argument must be str, not list f.write(new_line)if lines [0] .strip()。endswith(':')else f.write([new_line,* lines])TypeError:write()参数必须是str,而不是list

file.txt

Django 2.1:0
    djangoAPI1
    djangoAPI2

My Code 我的守则

import re
regex = r'(?<=:)\d*$'
def incr_patch_version(fname):
    with open(fname, 'r+') as f:
        lines = f.readlines()
        #print  (lines[0])
        new_line = re.sub(regex, lambda x: str(int(x.group()) + 1 if x.group().isnumeric() else 0), lines[0])
        f.seek(0)
        print (*lines)
        f.write(new_line ) if lines[0].strip().endswith(':') else f.write([new_line, *lines])
        #f.write(new_line ) if lines[0].strip().endswith(':') else f.writelines([new_line, *lines])
fname = 'file.txt'
incr_patch_version(fname)

if I am using f.write(new_line ) if lines[0].strip().endswith(':') else f.writelines([new_line, *lines]). 如果我使用f.write(new_line)如果lines [0] .strip()。endswith(':')else f.writelines([new_line,* lines])。 I am getting the below output 我得到以下输出

Django 2.1:3
Django 2.1:2
Django 2.1:1
Django 2.1:0
    djangoAPI1
    djangoAPI2

Desired Output file after 2 execution 2次执行后所需的输出文件

Django 2.1:2
    djangoAPI1
    djangoAPI2        
Django 2.1:1
    djangoAPI1
    djangoAPI2        
Django 2.1:0
    djangoAPI1
    djangoAPI2

You can update you code like below 您可以像下面一样更新代码

import re
import os

regex = r'(?<=:)\d*$'


def incr_patch_version(fname):
    with open(fname, 'r+') as f:
        lines = f.readlines()

        i = 1

        while i < len(lines)and ":" not in lines[i]:
            i += 1

        new_line = re.sub(regex, lambda x: str(int(x.group()) + 1 if x.group().isnumeric() else 0), lines[0])

        if not lines[i-1].endswith(os.linesep):
            lines[i-1] += os.linesep

        f.seek(0)
        new_lines = [new_line, *lines[1:i], *lines]
        f.writelines(new_lines)
        print(*new_lines)


fname = 'file.txt'
incr_patch_version(fname)

And the output in the file is like below 并且文件中的输出如下所示

Django 2.1:4
    djangoAPI1
    djangoAPI2
Django 2.1:3
    djangoAPI1
    djangoAPI2
Django 2.1:2
    djangoAPI1
    djangoAPI2
Django 2.1:1
    djangoAPI1
    djangoAPI2
Django 2.1:0
    djangoAPI1
    djangoAPI2

This is one approach. 这是一种方法。

import re
first_chunk = False
chunk = ""
with open(filename) as infile:
    content = infile.read()              #Read Content
    for line in content.splitlines():    #Iterate Lines
        match = re.match("\w+", line)    #Check for lable
        if match and first_chunk:        #Break if lable chunk found
            break
        elif match:
            first_chunk = True
            pattern = re.compile(r":(\d+)")
            chunk += pattern.sub(":{}".format(int(pattern.search(line).group(1))+ 1) ,  line)    #Increment count
        else:
            chunk += "\n" + line

with open(filename, "w") as outfile:            #Write back to file
    result = "{}\n{}".format(chunk, content)
    outfile.write(result)

Output: 输出:

Django 2.1:3
    djangoAPI1
    djangoAPI2
Django 2.1:2
    djangoAPI1
    djangoAPI2
Django 2.1:1
    djangoAPI1
    djangoAPI2
Django 2.1:0
    djangoAPI1
    djangoAPI2

Your actual issue is here : 你的实际问题在这里:

else f.write([new_line, *lines])

As you can see, you're giving a list as input to write method. 如您所见,您将列表作为write方法的输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError:write()参数必须是str,而不是保存.npy文件时的字节 - TypeError: write() argument must be str, not bytes while saving .npy file TypeError: write() 参数必须是 str,而不是 list - 如何将列表转换为要存储的文本文件? - TypeError: write() argument must be str, not list - How do I convert a list into a text file to be stored? 尝试将文本从 1 个文件添加到另一个文件时,获取 TypeError:write() 参数必须是 str,而不是列表 - getting TypeError: write() argument must be str, not list when trying to add text from 1 file to another 控制台文本到 csv 文件-类型错误:write() 参数必须是 str, - console text to csv file- TypeError: write() argument must be str, write()参数必须是str,而不是list - write() argument must be str, not list TypeError TypeError:connect() 参数 3 必须是 str,而不是 list - TypeError TypeError: connect() argument 3 must be str, not list TypeError:write()参数必须为str,而不是Text - TypeError: write() argument must be str, not Text 协助TypeError:write()参数必须为str,而不是None - Assistance with TypeError:write() argument must be str, not None 编码:TypeError:write()参数必须是str,而不是bytes - Encoding: TypeError: write() argument must be str, not bytes 类型错误:write() 参数必须是 str,而不是 HTTPResponse - TypeError: write() argument must be str, not HTTPResponse
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM