python - 如何在 python 中将一个文件的内容复制到另一个文件?-我还包括了我失败尝试的代码
问题描述
例如在这里我试图将 file1 的内容移动到文件 2 中;这是我尝试的代码,它不起作用。我的代码有什么问题,有没有更有效的方法?
file1 = open("textfile.txt", "r")
file2 = open("second textfile.txt","w")
lines = file1.readlines()
for i in range(len(lines)):
file2.write(lines[i]+"\n")
这个问题与其他类似类型的问题不同 - 因为它的解决方案特定于 python 中的编码。
解决方案
如果要将一个文件的内容复制到另一个文件中,可以这样做:
firstfile = "textfile.txt"
secondfile = "second textfile.txt"
with open(firstfile, "r") as file:
content = file.read()
file.close()
with open(secondfile, "w") as target:
target.write(content)
target.close()
推荐阅读
- angular - 模板的角度模板
- python - 使用 Bootstrap 无法在 Flask 中加载自定义 CSS
- javascript - InitTelInput — 如何在输入中设置正确的填充?
- reactjs - 使用不同的环境变量多次构建反应应用程序
- visual-studio-code - 在 VS Code 上启动和调试 Blazor 服务器和 webasm
- javascript - 在 JQuery 中使用正确的选择器来指示 HTML 表并使用 Bootstrap-table 函数时出现未捕获的错误
- javascript - 当 Iphone 中的显示缩放处于活动状态时,如何解决 React Native 中的字体大小问题?
- python - 如何在二维张量中获得相同值的张量索引?
- javascript - 如何将上下文方法传递给useEffect中的函数?
- javascript - Chrome:如果页面可滚动,则不会触发带有鼠标中键的辅助单击事件