程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了打开并读取名称转换为用户名并存储在另一个文件中的文件大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决打开并读取名称转换为用户名并存储在另一个文件中的文件?

开发过程中遇到打开并读取名称转换为用户名并存储在另一个文件中的文件的问题如何解决?下面主要结合日常开发的经验,给出你关于打开并读取名称转换为用户名并存储在另一个文件中的文件的解决方法建议,希望对你解决打开并读取名称转换为用户名并存储在另一个文件中的文件有所启发或帮助;

预科编程学生在这里。我正在尝试进行一些批处理模式处理,获取文件中的名称列表,打开所述文件,读取它,为文件中的每个名称分配一个用户名,然后将所述名称存储在另一个文件中。

这是我的代码:

# A program which takes a List of names from a file,creates a new file
# and makes a username based on each namE into it.

#first open each file
import String

def main():
    infilename = raw_input("what file are the names in")
    outfilename = raw_input("what file are the usernames going in?")

    #open the files

    infile = open(infilename,"r")
    outfile = open(outfilename,"w")

    data = infile.read()

    print data


main()   
#process each line in the file
for line in infile:
    #get the first and last names from line
    first,last = String.split(linE)
    #create a username
    uname = String.lower(first[0]+last[:7])
    #write it to output file
    outfile.write(uname+"\n")
    #close both files
infile.close()
outfile.close()

print "The usernames have been written to,",outfilename

一切似乎都很好,只是出现了错误代码:

TraceBACk (most recent call last):
  file "C:/Users/Manol/OneDrive/documents/Uni/ProgrAMMing/file Processing file/BatchUsernames.py",line 23,in <module>
    for line in infile:
nameError: name 'infile' is not defined
>>>

我不明白,因为我以为我在第 13 行定义了它

 infile = open(infilename,"r")

如果有人能指出我做错了什么,将不胜感激。 谢谢你的时间

  • 马诺斯

解决方法

您在 @H_911_7@main() 函数中定义了它,因此它是一个局部变量。 @H_911_7@main() 之外的任何函数都无法识别它。您可能也应该使用 data 代替,但同样,这是一个局部变量。一个可能的解决方案可能是这样的

import String

def main():
    infilename = raw_input("what file are the names in")
    outfilename = raw_input("what file are the usernames going in?")

    #open the files

    infile = open(infilename,"r")
    outfile = open(outfilename,"w")

    data = infile.read()
    
    for line in data:
        first,last = String.split(linE)
        
        uname = String.lower(first[0]+last[:7])
    
        outfile.write(uname+"\n")

    infile.close()
    outfile.close()

    print(data)
    print("The usernames have been written to,",outfileName)

main()   

大佬总结

以上是大佬教程为你收集整理的打开并读取名称转换为用户名并存储在另一个文件中的文件全部内容,希望文章能够帮你解决打开并读取名称转换为用户名并存储在另一个文件中的文件所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: