Error message:
file "new_prog.py, line 16, in <module>
newfile.write(line1)
AttributeError: 'str' object has no attribute 'write'
from sys import argv
from os.path import exists
newfile, nyfil = argv
print "First we erase is incase it already exists, filename is %r." % newfile
print "We are going to attempt to write a file and copy it."
newfile = raw_input("New filename: ")
print "Write the first line of the document"
line1 = raw_input("First line: ")
print "Write the second line of the document"
line2 = raw_input("Second line: ")
print "Write the last lines, can be coaherent"
lines = raw_input("last lines: ")
newfile.write(line1)
newfile.write("\n")
newfile.write(line2)
newfile.write("\n")
newfile.write(lines)
newfile.write("End of document")
newfile.close()
print "Closing %r for copying" % (newfile)
print "Checking if the new file exists. %r" % exists(nyfil)
raw_input("Press a key to continue")
nyfil = open(newfile, 'w')
nyfil = write(newfile)
nyfil.close()
print "All done, files are printed and copied"
from sys import argv
from os.path import exists
newfile, nyfil = argv
print "First we erase is incase it already exists, filename is %r." % newfile
print "We are going to attempt to write a file and copy it."
newfile = raw_input("New filename: ")
print "Write the first line of the document"
line1 = raw_input("First line: ")
print "Write the second line of the document"
line2 = raw_input("Second line: ")
print "Write the last lines, can be coaherent"
lines = raw_input("last lines: ")
with open(newfile, 'w') as f:
f.write(line1)
f.write("\n")
f.write(line2)
f.write("\n")
f.write(lines)
f.write("\n")
f.write ("End of document")
print "Closing %r for copying" % (newfile)
print "Checking if the new file exists. %r" % exists(nyfil)
raw_input("Press a key to continue")
with open(newfile, 'w') as f:
f.write(nyfil)
print "All done, files are printed and copied"
答案 0 :(得分:0)
newfile = raw_input("New filename: ")
newfile是一个字符串而不是文件对象,因此错误是有意义的。您需要执行以下操作:
with open(newfile, "w") as f:
f.write(line1)
f.write("\n")
etc....
我不完全确定你的代码是做什么的,但是这个例子将展示如何将文件名作为命令行arg并写入你输入的行:
def write_to_file(newfile):
print "You entered filename {}".format(newfile) # string formatting
print "We are going to write to a file."
newfile = raw_input("New filename: ")
print "Write the first line of the document"
line1 = raw_input("First line: ")
print "Write the second line of the document"
line2 = raw_input("Second line: ")
print "Write the last lines, can be coaherent"
lines = raw_input("last lines: ")
with open(newfile, "w") as f: # use with to open files as it closes them automatically
f.write(line1)
f.write("\n")
f.write(line2)
f.write("\n")
f.write(lines)
f.write("End of document")
print "Finished writing to {}".format(newfile)
if __name__ =="__main__":
write_to_file(sys.argv[1]) # command line arg
将脚本保存为foo.py
,然后使用python foo.py foo.txt
运行该脚本,它将创建并将您的输入写入foo.txt
文件。