这是困难的学习python练习之一的问题。练习是将一个文件复制到另一个文件,我可以正常工作,但是我想扩展一下代码以打印刚刚写入的文件。这是代码:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
#creates a variable called "in_file" from the argv "from_file", opens it and reads it.
in_file = open(from_file).read()
print(f"The contents of 'from_file' is:\n {in_file}")
print(f"The input file is {len(in_file)} bytes long")
print(f"Does the output file exist? {exists(to_file)}")
print(f"Ready, hit RETURN to contiune, CTRC-C to abort")
input(">")
#creates variable "out_file" and opens the "to file" argv 'w' means writable
out_file = open(to_file, 'w')
#writes data from "in_file to "out_file"
out_file.write(in_file)
print("Alright, all done")
#Try to print the file we wrote to
blah = open(to_file).read()
print(f"We printed: {blah}")
运行此脚本时,会发生以下情况:
$ python3 ex17.py test.text new_file.text
Copying from test.text to new_file.text
The contents of 'from_file' is:
This is a test file.
The input file is 21 bytes long
Does the output file exist? True
Ready, hit RETURN to contiune, CTRC-C to abort
>
Alright, all done
We printed:
所以我的问题是什么也没打印出来。如果我选择“ new_file.text”,内容是正确的,但是代码显然出了点问题,因为它根本没有打印出来。
有什么建议吗?
答案 0 :(得分:1)
我刚刚测试过。这是因为out_file没有关闭。将BestTestFit <- grplasso(Outcome ~. , data = testdata, lambda = lambdaopt, model = LogReg(), center = TRUE,standardize = TRUE)
p1 = BestTestFit$fitted
添加到out_file.close()
后,当然,建议您使用out_file.write(in_file)
而不是打开文件。