Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

python - How to give a name for a file?

For every iteration in my loop for, I need to give 'the number of my iteration' as a name for the file, for example, the goal is to save:

my first iteration in the first file.
my second iteration in the second file.
....

I use for that the library numpy, but my code doesn't give me the solution that i need, in fact my actual code oblige me to enter the name of the file after each iteration, that is easy if I have 6 or 7 iteration, but i am in the case that I have 100 iteration, it doesn't make sense:

for line, a in enumerate(Plaintxt_file):
    #instruction
    #result
    fileName = raw_input()
    if(fileName!='end'):
        fileName = r'C:\Users\My_resul\Win_My_Scripts\'+fileName
        np.save(fileName+'.npy',Result)
ser.close()

I would be very grateful if you could help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create your file name from the line number:

for line, a in enumerate(Plaintxt_file):
    fileName = r'C:UsersMy_resulWin_My_Scriptsfile_{}.npy'.format(line)
    np.save(fileName, Result)

This start with file name file_0.npy. If you like to start with 1, specify the starting index in enumerate:

for line, a in enumerate(Plaintxt_file, 1):

Of course, this assumes you don't need line starting with 0 anywhere else.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...