Python, how to write string and function to text
我不熟悉python,所以如果这是一个基本的错误,我将尝试将某些信息写入一个txt文件(OS是Windows)。
我想将"平台架构:"作为文本编写,并将platform.architecture的输出写入一个文件。这是我的当前代码:
1 2 3 4 | import.platform file = open('C:\\Users\\user\\Desktop\\pc info.txt','w') file.write('Platform architecture:'),platform.architecture |
当我点击run时,一个名为pc info的文件会按预期在我的桌面上生成,但在该文件中,只有
有什么想法吗?
调试:
SyntaxError: invalid syntax on line 1
1 | import.platform |
要说:
1 | import platform |
你要称为"
1 | file.write('Platform architecture:'),platform.architecture |
要说:
1 | file.write('Platform architectue: {}'.format(platform.architecture())) |
四:
使用
1 2 3 4 5 6 | import platform print(platform.architecture()) # ('64bit', 'WindowsPE') (in my case) logFile = 'Path\\to\\your\\file' with open(logFile, 'w') as f: f.write('Platform architectue: {}'.format(platform.architecture())) |
输出:
1 | Platform architectue: ('64bit', 'WindowsPE') |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | # importing the platform module from the site-packages in python import platform # adding the file absolute path with name, so you can run the script anywhere # in you system file_path =r'C:\Users\user\file.txt' """ creating the file at given path with the write permission, using with instead of directly open. (why go here to know -> https://stackoverflow.com/questions/31334061/file-read-using-open-vs-with-open """ with open(file_path,'w+') as file: file.write('Platform architecture : {}'.format(platform.architecture())) """ writing the output of platform.architecture() command in the file. using `str.format()` function for better readablity. """ |
1 2 3 | import platform with open('C:\\Users\\user\\Desktop\\pc_info.txt','w') as file: file.write('Platform architecture: {}'.format(platform.architecture())) |