![](/img/trans.png)
[英]How to modify multiple columns and rows in a csv file using python 2.7.9
[英]Removing second row of csv file and modify the columns using Python
我目前使用下面提供的代碼將 CSV 文件從一個文件夾復制到另一個文件夾,並刪除其中存在的 CSV 文件的第二行。
上面的代碼從所有CSV文件中刪除了第二行,即第1行,但同時,它在所有CSV文件中的每一行之后添加了一個空行。
示例- 實際 CSV:
| row_no | name | test |
| | | |
| | | input |
-------------------------
| 0 | abc | 123 |
| 1 | def | 456 |
| 2 | ghi | 789 |
| 3 | jkl | 101 |
應用代碼后:
| row_no | name | test |
| | | |
| | | input |
-------------------------
| 0 | abc | 123 |
| | | |
| 2 | ghi | 789 |
| | | |
| 3 | jkl | 101 |
問題 1:如何刪除空行?
問題2:我想去掉列名中的空格;
列示例:
| test |
| | -> |testinput|
| input |
謝謝
Q1:默認情況下, csv.writer
以“excel”方言寫入 CSV 文件,這意味着行結尾是\\r\\n
。 嘗試將csv.writer
設置為"unix"
模式,該模式的行尾是普通的\\n
。
Q2:只需使用str.replace
將所有空格替換為str.replace
。
這是您的代碼的修改版本:
import glob, os, shutil, csv
source_path = "/home/Desktop/Output/"
dest_path = "/home/Desktop/Output2/"
file_read_path = "/home/Desktop/Output2/*.csv"
## Code to copy .csv files from one folder to another
for csv_file in glob.iglob(os.path.join(source_path, "*.csv"), recursive = True):
shutil.copy(csv_file, dest_path)
## Code to delete the second row in all .CSV files
for filename in glob.glob(file_read_path):
with open(filename, "r") as file:
reader = list(csv.reader(file , delimiter = ","))
# Remove second row
del reader[2] # 0=columnnames, 1=first data row, 2=second data row
# Remove spaces from column names
reader[0] = [colname.replace(" ", "") for colname in reader[0]]
with open(filename, "w") as output:
# Set csv.writer to output files in the "unix" dialect
writer = csv.writer(output, delimiter = ",", dialect="unix")
for row in reader:
writer.writerow(row)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.