文本文件未写入,python3

时间:2018-12-17 11:34:34

标签: python python-3.x

def getlink():
with open('findlink.txt') as infile, open('extractlink.txt', 'w') as outfile:
    copy = False
    for line in infile:
        if line.strip() == "](":
            copy = True
        if copy:
            outfile.write(line)
        if line.strip() == ")":
            copy = False
            print("extractlink written.")
            infile.close()
            outfile.close()

def part3():
    with open ('findlink.txt', 'w') as findlink:
    findlink.write("[Testing](Test)")
    findlink.close() 
    print("findlink written and closed.")
getlink()

def run_bot():
    getlink() #Already have findlink.txt written

激活part3()时,文本将按预期方式写入findlink.txt,但是激活getlink()时,则永远不会写入extractlink.txt。

我从2013/2016年的帖子中收集了当前代码,有人对为什么这可能不起作用有任何想法吗?

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

def getlink():
    with open('findlink.txt') as infile: 
        data = infile.readlines()

    with open('extractlink.txt', 'w') as outfile:
        copy = False
        for line in data:
            if line.strip() == "](":
                copy = True
            if copy:
                outfile.write(line)
            if line.strip() == ")":
                copy = False
                print("extractlink written.")
                outfile.close()
                extractlink()
                return