Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Python - How can I make a variable used inside a function have iterative values?

I'm struggling to word this question, I may deserve a downvote or two - sorry.

Simplified problem - I have a function that takes an input of an f string, and that f string inputs variable X into itself. X will be an element from a list of letters in the alphabet (ls) for this example. Currently my function outputs the letter 'Z'. I need the function to output the letter 'Z' into a text file, then 'Y' into a new text file and etc. My problem is that I'm struggling to iterate through the list itself, whilst using each element independently.

What I'd like to do is separate my alphabet file into individual files for each letter. So far however most functions I have made to output the current letter minus one index position give me unsupported operand errors for '-' with list and int, tuple and int etc, or other TypeErrors.

Function use:

write('txt.txt', 0, f'The letter: {X}' + '
')

The write function takes parameters (file, line, text).

How could I make X, be X, and then be X-1/X+1? Currently X is defined as:

for individual in ls:
     pass

X = individual.strip()

My shabby attempts go something along the lines of:

def decrement(x):
     x = x - 1

A = decrement(ls)

I hope this makes sense. I've tried to simplify it as much as possible. I'm sorry I wasn't able to find a working example of this myself. If my pseudo example sucks let me know so I can replace it.


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

1 Answer

0 votes
by (71.8m points)

As you mentioned, it's hard to tell what you want, but is I'm assuming it's a directory of files with a single letter from the alphabet. Here's how I would do it:

import pathlib
import string

# make the directory to hold the files
file_dir = pathlib.Path("~/tmp/letterfiles").expanduser()
file_dir.mkdir(exist_ok=True, parents=True)
# go through all the letters and write some text to files
for letter in string.ascii_lowercase:
    pathlib.Path(file_dir, f"{letter}.txt").write_text(f"The letter: {letter}
")

Here's the result:

$ python3 tmp.py
$ ls ~/tmp/letterfiles
a.txt  c.txt  e.txt  g.txt  i.txt  k.txt  m.txt  o.txt  q.txt  s.txt  u.txt  w.txt  y.txt
b.txt  d.txt  f.txt  h.txt  j.txt  l.txt  n.txt  p.txt  r.txt  t.txt  v.txt  x.txt  z.txt
$ cat ~/tmp/letterfiles/a.txt
The letter: a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...