在Python中以特定格式保存文件名。

huangapple go评论55阅读模式
英文:

Saving filename in a specific format in Python

问题

当前输出文件名是:

All_values_{Start}_{End}_{Stepsize}

期望的输出是:

All_values_0_500001_1000
英文:

I am generating numbers in a specific range with a specific stepsize and saving to a .txt file. But I want to save the filename in a specific format. I present the current and expected output.

Start=0
End=500001
Stepsize=1000
for i in range(Start,End,Stepsize):
    #print(i)
    
    with open('All_values_{Start}_{End}_{Stepsize}.txt', 'a') as f:
        #writer = csv.writer(f)   
        #print(" =",i)
        f.writelines('\n')
        f.write(str(i))

The current output in terms of file naming is

All_values_{Start}_{End}_{Stepsize}

The expected output is

All_values_0_500001_1000

答案1

得分: 3

Use f-strings, just add an f to this line:

    with open(f'All_values_{Start}_{End}_{Stepsize}.txt', 'a') as f:
英文:

Use f-strings, just add an f to this line:

    with open(f'All_values_{Start}_{End}_{Stepsize}.txt', 'a') as f:

huangapple
  • 本文由 发表于 2023年6月19日 13:46:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503900.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定