如何把文本文件放在了Python脚本所在的同一目录
时间: 2024-01-22 19:18:22 浏览: 298
可以使用Python内置的`os`模块来获取当前脚本所在的目录,然后使用相对路径的方式打开文本文件。具体操作如下:
``` python
import os
# 获取当前脚本所在的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 打开文本文件
with open(os.path.join(current_dir, 'text_file.txt'), 'r') as f:
contents = f.read()
```
在上述代码中,`os.path.abspath(__file__)`返回当前脚本的绝对路径,`os.path.dirname()`方法获取该路径的目录部分,最终得到当前脚本所在的目录。然后使用`os.path.join()`方法将当前目录和文件名拼接成文本文件的相对路径,再使用`open()`函数打开文件。
相关问题
python批量提取同一目录下所有PDF电子发票信息转存到EXCEL
在Python中,你可以使用`PyPDF2`库来处理PDF文件,并结合`pandas`库来创建Excel文件。这里是一个简单的步骤指南:
首先,确保安装了所需的库,如果没有,可以使用pip安装:
```bash
pip install PyPDF2 pandas openpyxl
```
接下来,编写一个Python脚本来批量提取PDF文件中的数据并转换到Excel:
```python
import os
import PyPDF2
import pandas as pd
# 定义函数来读取单个PDF并提取相关信息
def extract_info_from_pdf(pdf_path):
with open(pdf_path, 'rb') as file:
pdf = PyPDF2.PdfFileReader(file)
info = []
for page_num in range(pdf.getNumPages()):
# 假设发票信息在第一页
text = pdf.getPage(page_num).extractText()
# 根据实际结构解析文本,提取你需要的数据,例如:
invoice_data = {'发票号码': text.split('发票号码:')[1].split('\n')[0],
'金额': text.split('金额:')[1].split('\n')[0]}
info.append(invoice_data)
return info
# 定义工作目录和目标Excel文件名
dir_path = 'your_directory_path' # 替换为你需要提取的PDF文件夹路径
output_file = 'invoices.xlsx'
# 遍历目录下的所有PDF文件
pdf_files = [f for f in os.listdir(dir_path) if f.endswith('.pdf')]
data_list = []
for pdf in pdf_files:
data_list.extend(extract_info_from_pdf(os.path.join(dir_path, pdf)))
# 将数据列表转换为DataFrame并保存到Excel
df = pd.DataFrame(data_list)
df.to_excel(output_file, index=False)
假设文件 data.txt 中有若干行,每行一个整数,编写程序读取所有整数,将其按降序排序后再写文本文件 data des.txt 中。假设文本文件与程序文件位于同一目录下。
为了实现这个需求,你可以使用Python语言编写一个简单的脚本。以下是步骤:
1. 打开并读取 `data.txt` 文件中的所有整数。可以逐行读取,每一行转换成整数并添加到列表中。
```python
with open('data.txt', 'r') as file:
numbers = [int(line) for line in file]
```
2. 对数字列表进行降序排序。
```python
numbers.sort(reverse=True)
```
3. 将排序后的数字写入 `data des.txt` 文件中。
```python
with open('data des.txt', 'w') as file:
for number in numbers:
file.write(str(number) + '\n')
```
完整代码示例:
```python
# Step 1: Read and sort the numbers
with open('data.txt', 'r') as file:
numbers = [int(line) for line in file]
numbers.sort(reverse=True)
# Step 2: Write sorted numbers to a new file
with open('data des.txt', 'w') as file:
for number in numbers:
file.write(str(number) + '\n')
阅读全文
相关推荐














