将文件内容复制到新Fi中

2024-05-18 06:12:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个Python脚本,它获取文本文件的内容,并将其复制到程序自己创建的新文件中。你知道吗

这是我目前正在测试的代码:

from datetime import datetime

errorLogPath = datetime.strftime(datetime.now(), '%Y%m%d_%H:%M') + ".log"

with open("Report.log") as logFile:
    with open(errorLogPath, 'w') as errorLog:
        for line in logFile:
            errorLog.write(line)

当前已创建新文件,但该文件完全为空且文件名错误。文件名应该是YYYYMMDD_HH:MM.log,而我得到的文件名不显示分钟数,文件为空。你知道吗

EDIT:删除了一个不必要的if语句,但代码仍然无法运行:\


Tags: 文件代码脚本log内容datetime文件名as
3条回答

问题出在您的路径名上,:是windows中的保留字符,下面是whole list

  • <;(小于)
  • >;(大于)
  • :(冒号)
  • “(双引号)
  • /(正斜杠)
  • \(反斜杠)
  • |(立杆或立管)
  • 什么?(问号)
    • (星号)

结肠称为:

A disk designator with a backslash, for example "C:\" or "d:\".

因此,正确的解决方案是更改errorLogPath以删除:字符。你知道吗

那么,复制文件的最佳方法就是使用^{}

from datetime import datetime
from shutil import copy

error_log_path = datetime.strftime(datetime.now(), '%Y%m%d_%H_%M') + ".log"
log_file_path = "Report.log"
copy(log_file_path, error_log_path)

注意:

  • 您可以用一个with语句打开多个文件。你知道吗
  • 最好不要在python中使用lower_case而不是camelCase作为变量名。你知道吗

在python中复制文件而不使用shutil模块的最简单方法是:

with open("Report.log") as logFile, open(errorLogPath, 'w') as errorLog:
    errorlog.writelines(logFile)

要使用shutil模块:

import shutil
shutil.copy("Report.log", errorLogPath)

试试这个,这个对我很有用:

from datetime import datetime
import csv
errorLogPath = datetime.strftime(datetime.now(), '%Y%m%d_%H:%M') + ".log"
ff = open(errorLogPath, 'w')
csvwriter = csv.writer(ff)
with open("Report.log","r") as logFile:
    reader = csv.reader(logFile)
    for line in reader:
        if "ROW" in line:
            csvwriter.writerow(line)
        else:
            continue

    ff.close()

相关问题 更多 >