如何打开输入文件,对其进行编辑,然后使用python将其保存为其他名称

时间:2019-07-08 05:38:33

标签: python file

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

我非常喜欢不导入任何内容。

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

应有尽有,但我不知道从哪里开始下一步。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

这里是:

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