如何用Python循环从作者数量不一的TXT文件提取作者姓名
Absolutely! Looping through multiple author files (no matter how many names each contains) is totally achievable in Python, and it’s a perfect way to build on your existing single-file script. Let’s walk through a straightforward, beginner-friendly solution.
1. Find all your author files automatically
First, we need a way to grab all those authors*.txt files without typing each filename manually. The glob module is perfect for this—it lets you search for files using wildcard patterns.
import glob # Get all files starting with "authors" and ending with ".txt" file_paths = glob.glob("authors*.txt")
This will give you a list of paths to every matching file (like ["authors1.txt", "authors3.txt", ...]).
2. Loop through each file and extract authors
Now, we’ll loop over each file path, and reuse your existing extraction logic inside the loop. Since your files have varying numbers of authors, we just need to make sure we capture all names in each file—no hardcoding counts needed!
Assuming your single-file script reads each author from a new line (adjust this part if your files use a different format, like commas):
import glob file_paths = glob.glob("authors*.txt") for file_path in file_paths: # Open the file safely using a 'with' statement (handles closing automatically) with open(file_path, "r", encoding="utf-8") as f: # Extract non-empty lines (strip removes extra spaces/newlines) authors = [line.strip() for line in f if line.strip()] # Print or process the authors as needed print(f"📄 {file_path} has {len(authors)} authors: {authors}") # Optional: Save to a single CSV or do other tasks here # For example, append to a master list: # all_authors.extend(authors)
3. Handle edge cases (optional but helpful)
As a beginner, it’s good to add checks for things like empty files or files that can’t be opened:
import glob file_paths = glob.glob("authors*.txt") all_authors = [] for file_path in file_paths: try: with open(file_path, "r", encoding="utf-8") as f: authors = [line.strip() for line in f if line.strip()] if authors: print(f"📄 {file_path}: {authors}") all_authors.extend(authors) else: print(f"⚠️ {file_path} has no authors listed.") except Exception as e: print(f"❌ Error reading {file_path}: {str(e)}") # After processing all files, you can use the all_authors list print(f"\nTotal unique authors found: {len(set(all_authors))}")
Key Notes for Your Existing Script
If your current single-file code uses a different method to extract authors (e.g., splitting a comma-separated line), just replace the authors = [...] line with your existing logic. The loop structure stays exactly the same—you’re just running that logic once per file.
内容的提问来源于stack exchange,提问作者ahmed redha

