简体   繁体   English

创建和写入文件-Python

[英]Creating and writing to file - Python

I want to create a file with a name according to a variable. 我想根据变量创建一个文件名。 That is my first problem and then I want to write what is printed to the screen in console to that file. 那是我的第一个问题,然后我想将打印在控制台屏幕上的内容写入该文件。

This is what I have, I am currently getting an error at the .open. 这就是我所拥有的,.open当前出现错误。 - 'EOL while scanning string literal'. -“在扫描字符串文字时停止运行”。 However I guess there will be more errors to follow that. 但是我想将会有更多的错误。

saveFile.open((fileName)".txt,'w')
saveFile.write("Final Quote Price: £", format(FinalPrice, '.2f'), "Plus VAT")
saveFile.close()

I just put an example in the .write part but I want it to write certain parts of what is printed to the screen in console to file - is that possible? 我只是在.write部分中放置了一个示例,但我希望它将控制台中打印到屏幕上的某些内容写到文件中-可能吗?

i think u missed a + between your variable and string literal. 我认为您错过了您的变量和字符串文字之间的+ saveFile.open((fileName)+".txt,'w')

There are missing quotes: 缺少引号:

saveFile = open(fileName+".txt",'w')
saveFile.write("Final Quote Price: £{:.2f} Plus VAT".format(FinalPrice))
saveFile.close()
saveFile.open(fileName + ".txt",'w')
saveFile.write("Final Quote Price: £" + format(FinalPrice, '.2f') + "Plus VAT")
saveFile.close()

This should work 这应该工作

There is a double quota lost in your code, try this, 您的代码丢失了双重配额,请尝试以下操作,

saveFile.open((fileName)+".txt",'w')
saveFile.write("Final Quote Price: £", format(FinalPrice, '.2f'), "Plus VAT")
saveFile.close()

To write and to read date from a file with a variable name: 要从具有变量名的文件中写入和读取日期:

fileName = 'fileData'
finalPrice = 12.003321

fileObj = open(fileName + ".txt", 'w')
fileObj.write("Final Quote Price: £" + format(finalPrice, '.2f') + "Plus VAT")
fileObj.close()

with open(fileName + '.txt', 'r') as file:
    fileString = file.read()
    print("Line: " + fileString)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM