بکندباز

اضافه کردن محتوای یک فایل متنی به فایل دیگر در پایتون

با داشتن نام دو فایل وارد شده توسط کاربر، می خواهیم محتوای فایل دوم را به محتوای فایل اول اضافه کنیم.
مثال

Input :
file1.txt
file2.txt

Output :
Content of first file (before appending) - hello 
Content of second file (before appending) - world
Content of first file (after appending) - hello world
Content of second file (after appending) - world

 

الگوریتم:

  1. نام فایل ها را وارد کنید.
  2. با استفاده از تابع open()‎ هر دو فایل را در حالت فقط خواندنی باز کنید.
  3. محتویات فایل ها را قبل از اضافه کردن با استفاده از تابع read()‎ چاپ کنید.
  4. هر دو فایل را با استفاده از تابع ()close ببندید.
  5. فایل اول را در مد الحاق (a) و فایل دوم را در مد خواندن (r) باز کنید.
  6. با استفاده از تابع write()‎ محتویات فایل دوم را به فایل اول اضافه کنید.
  7. با استفاده از تابع seek()‎ مکان نمای فایل ها را در ابتدا قرار دهید تا محتوا از اول چاپ شود.
  8. محتویات فایل های ضمیمه شده را چاپ کنید.
  9. هر دو فایل را ببندید.
# entering the file names
firstfile = input("Enter the name of first file ")
secondfile = input("Enter the name of second file ")

# opening both files in read only mode to read initial contents
f1 = open(firstfile, 'r')
f2 = open(secondfile, 'r')

# printing the contents of the file before appending
print('content of first file before appending -', f1.read()‎)
print('content of second file before appending -', f2.read()‎)

# closing the files
f1.close()‎
f2.close()‎

# opening first file in append mode and second file in read mode
f1 = open(firstfile, 'a+')
f2 = open(secondfile, 'r')

# appending the contents of the second file to the first file
f1.write(f2.read()‎)

# relocating the cursor of the files at the beginning
f1.seek(0)
f2.seek(0)

# printing the contents of the files after appendng
print('content of first file after appending -', f1.read()‎)
print('content of second file after appending -', f2.read()‎)

# closing the files
f1.close()‎
f2.close()‎
zohreh

مدیر وب سایت بکندباز

دیدگاه‌ها

*
*