固定代码;
if os.path.isfile(external_file):
with open(external_file) as in_f:
name = in_f.read()
else:
name = raw_input("What's your name?")
with open(external_file, "w") as out_f:
out_f.write(name)
问题是。
它指的是使用它的每台计算机,其名称存储在.txt中。 我需要为每个mac地址/ ip /计算机提供不同的.txt
我还需要根据用户的命令更改名称
如果.txt中没有名字,它也不会要求提供姓名吗?
答案 0 :(得分:0)
您可以尝试这样做,首先只需询问用户的名字,然后检查文件names.txt
是否存在,如果不存在,则创建一个名称为name的新文件。 txt并将用户的名称附加到其中。如果该文件现在存在,请检查它是否包含用户的名称,如果该文件包含,则说出“嗨+名称”,然后将该名称附加到该文件中。
以下是对代码的快速而肮脏的修复(可以进一步改进!):
import os
#hard code the path to the external file
external_file = 'names.txt'
#Ask the user's name
name = raw_input("What's your name?")
#if file exists, use it to load name, else create a new file
if not os.path.exists(external_file):
with open(external_file, "a") as f: # using "a" will append to the file
f.write(name)
f.write("\n")
f.close()
else:
#if file exists, use it to load name, else ask user
with open(external_file, "r+") as f:# r+ open a file for reading & writing
lines = f.read().split('\n') # split the names
#print lines
if name in lines:
print "Hi {}".format(name)
else:
f.seek(0,2) # Resolves an issue in Windows
f.write(name)
f.write("\n")
f.close()
更新:修改后的版本仅检查带有编码的名称:
import os
#hard code the path to the external file
external_file = 'names.txt'
username = 'testuser'# Our hardcoded name
#if file doesn' exists, create a new file
if not os.path.exists(external_file):
#Ask the user's name
name = raw_input("What's your name?")
with open(external_file, "a") as f: # using "a" will append to the file
f.write(name)# Write the name to names.txt
f.write("\n")
f.close()
else:
#if file exists, use it to load name, else ask user
with open(external_file, "r+") as f:# r+ open a file for reading & writing
lines = f.read().split('\n') # split the names
print lines
if username in lines: #Check if the file has any username as 'testuser'
print "Hi {}".format(username)
else: # If there is no username as 'testuser' then ask for a name
name = raw_input("What's your name?")
f.seek(0,2) # Resolves an issue in Windows
f.write(name)# Write the name to names.txt
f.write("\n")
f.close()
使用file.seek()
的原因是here。