Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何打开输入文件,对其进行编辑,然后使用python以其他名称保存_Python_File - Fatal编程技术网

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

如何打开输入文件,对其进行编辑,然后使用python以其他名称保存,python,file,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)) 结果是应该的,但我不知道下一步该从哪里开始。这里是:

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

我非常不喜欢进口任何东西

file1 = open('file1.txt')
def wordCount(file1):
    contents = file1.read()
    file1.close()
    print(contents)
    return len(contents)
print(wordCount(file1))
结果是应该的,但我不知道下一步该从哪里开始。

这里是:

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

因此,是否要将
file1.txt
更改为
file2.txt
?如果要在file2中包含长度,则可能会重复?请使用file2。打开后写入(“您的内容”)
# 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)