【问题标题】:How to open an input file, edit it, then save it with a different name with python如何打开一个输入文件,编辑它,然后用 python 用不同的名字保存它
【发布时间】:2019-07-08 05:38:33
【问题描述】:

我想打开一个名为 file1.txt 的文本文件,计算长度,然后用名称 file2.txt 关闭它。

我非常喜欢不导入任何东西。

file1 = open('file1.txt')
def wordCount(file1):
    contents = file1.read()
    file1.close()
    print(contents)
    return len(contents)
print(wordCount(file1))

它应该会出现,但我不知道该过程的下一步从哪里开始。

【问题讨论】:

标签: python file


【解决方案1】:
# Copying then editing files
local_saved = []
with open("file1.txt", "r") as f:
    local_saved.append(f.read())

with open("file2.txt", "w+") as f:
    text_to_write = local_saved[0]
    # Edit text_to_write below. 
    # Can be deleted (text_to_write = "") or changed in any way as if it were a normal string.
    # ...

    f.write(text_to_write)

【讨论】:

    【解决方案2】:

    这里是:

        file1 = open('file1.txt')
        def wordCount(file1):
            contents = file1.read()
            file2=open('file2.txt','w')
            file2.write(contents)
            file2.close()
            file1.close()
            print(contents)
            return len(contents)
        print(wordCount(file1))
    

    【讨论】:

    • 如果我想在 file2 中包含长度怎么办?
    • 打开后使用file2.write('your_content')
    猜你喜欢
    • 2011-01-05
    • 1970-01-01
    • 2022-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多