【问题标题】:Python , Get the username in windows and then save it in a text filePython,在windows中获取用户名,然后保存到文本文件中
【发布时间】:2018-06-11 10:05:40
【问题描述】:

我知道使用getpass.getuser() 命令可以获得用户名,但如何将其保存在文本文件中?所以我想让python找到用户名,然后保存在下面的文件username.txt中

脚本:

os.path.join('..','Documents and Settings','USERNAME','Desktop'))

(正在使用 Python 2.7 版)

【问题讨论】:

  • Python Save to file的可能重复
  • 把它加到一个变量里然后让python把这个变量放到一个txt文档里?
  • 到目前为止,您的脚本构造了字符串'../Documents and Settings/USERNAME/Desktop',甚至没有存储它。没有尝试打开甚至写入文件。
  • 顺便说一句,为什么是 python 2.7 而不是 3?只是好奇...
  • 我很确定一个简单的:os.system('whoami > user.txt') 会将用户名存储在一个文件中。

标签: python python-2.7 file


【解决方案1】:

你必须打开一个 txt 文件,构造你的字符串然后写入它。

import getpass

# get your username
username = getpass.getuser()

# open a txt file in append mode
log = open('username.txt', 'a')

# create your string
string = os.path.join('..','Documents and Settings',username,'Desktop')

# save and close the file
log.write(string)
log.close()

或者你可以使用 pythons 'with' 语句来确保文件被正确关闭。

import getpass

# get your username
username = getpass.getuser()

# create your string
string = os.path.join('..','Documents and Settings',username,'Desktop')

with open('username.txt') as file:
    file.write(string)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    相关资源
    最近更新 更多