2014-10-10 84 views
1

任何人都可以帮助我完成此任务。我是Python的新手。我试图做到这一点: 文件名应该是硬代码名称叫做:Server_Information.txt和第二列应该由用户输入插入,但日期戳。 内置者:李四 构建日期:%d%M%Y 生成原因:游乐场 请求者:李四从用户输入创建文件

也许我可以用这个测试脚本,但第一列不会在最后的测试文件显示。

谢谢你对任何人可以帮助

from sys import argv 

script, filename = argv 

print "We're going to erase %r." % filename 
print "If you don't want that, hit CTRL-C (^C)." 
print "If you do want that, hit RETURN." 

raw_input("?") 

print "Opening the file..." 
target = open(filename, 'w') 

print "Truncating the file. Goodbye!" 
target.truncate() 

print "Now I'm going to ask you for three lines." 

line1 = raw_input("Built By : ") 
line2 = raw_input("Build Date: %d%m%y ") 
line3 = raw_input("Build Reason: ") 
line4 = raw_input("Requestor: ") 

print "I'm going to write these to the file." 

target.write(line1) 
target.write("\n") 
target.write(line2) 
target.write("\n") 
target.write(line3) 
target.write("\n") 
target.write(line4) 

print "And finally, we close it." 
target.close() 

回答

0

尝试写此之后重新打开该文件,因为现在你不记录邀请作为文件。

target.write('%s: %s\n' % ('Built By', line1)) 
target.write('%s: %s\n' % ('Build Date', line2)) 
target.write('%s: %s\n' % ('Build Reason', line3)) 
target.write('%s: %s\n' % ('Requestor', line4)) 
+0

同样在这里,我用你的替换我的target.write,不工作给我错误。 – pirulo 2014-10-10 13:40:41

1

尝试关闭和截断()

target.close() 
target = open(filename, 'w') 
# ask for user input here 
# and close file 
+0

我不能让它工作.. Thks – pirulo 2014-10-10 13:42:40

0

由于raw_input只返回由用户输入的输入,不包括你使用的提示信息,所以你需要将这些信息手动添加到line1,像这样:

line1 = "Built By : " + raw_input("Built By : ") 

并为line2我想你想自动生成它而不是要求用户输入,你可以这样做:

line2 = "Build Date: " + time.strftime("%d%m%Y", time.localtime()) 
+0

WKplus,谢谢您的输入。我无法让它工作。我收到的错误名称未定义。我运行在调试器模式下。 python -m pdb script.py但作为儿子,我把它死的文件的名称。 – pirulo 2014-10-10 13:28:48

+0

@pirulo在使用'time.strftime'之前,您需要添加'import time'。 – WKPlus 2014-10-11 02:18:18

+0

谢谢,它就像一个魅力..! – pirulo 2014-10-11 03:39:47